注册 登录
编程论坛 C++教室

自己写的string类

fhqihfd123 发布于 2010-10-20 16:10, 1262 次点击

#include <iostream>
using namespace std;
class String
{
    char *ptr;
    public:
    String();
    ~String();
    explicit String(const char *p);
    String(const String&s);
    String& operator=(const String& rhs);
     friend ostream&operator<<(ostream& os,const String& s);
    };
String::String()
{
    ptr=new char[1];
    ptr[0]='\0';
}
String::~String()
{
    delete[]ptr;
}
String::String(const char*p)
{
    ptr=new char[strlen(p)+1];
    strcpy(ptr,p);
}
String::String(const String&s)
{
    ptr=new char[strlen(s.ptr)+1];
    strcpy(ptr,s.ptr);
}
String& String::operator=(const String& rhs)
{
    if(this!=&rhs)
    {
    delete[]ptr;
    ptr=new char[strlen(rhs.ptr)+1];
    strcpy(ptr,rhs.ptr);
    }
    return *this;
   
}
ostream&operator<<(ostream& os,const String& s)
{
    os<<s.ptr;
    return os;
}
int main()
{
       String s1;
       String s2("abcd");
       String s3=s2;
       s1=s2;
       s2=s2;
       cout<<s2<<endl;         
  
    system("pause");
      return 0;
}
7 回复
#2
system32882010-10-20 17:09
学习了,高手啊。刚接触C++的类,感觉好复杂,好难懂啊
#3
lyj2010lyj2010-10-20 19:12
复杂,一点提示都没有!
#4
pangding2010-10-20 22:18
值得鼓励。
楼主可以试着再去实现一些其它 string 类里有的函数。
#5
zhoufeng19882010-10-21 09:15
顶一下~支持
#6
fhqihfd1232010-10-22 14:28
哪个地方看不懂,,可以问我?
#7
蜗牛前行2010-12-14 14:32
为什么我运行一下,,有好几个错误?
#8
laoyang1032010-12-14 15:29
String& String::operator=(const String& rhs)
{
    if(this!=&rhs)
    {
    delete[]ptr;
    ptr=new char[strlen(rhs.ptr)+1];
    strcpy(ptr,rhs.ptr);
    }
    return *this;
   
}
呵呵  这就是楼主所谓的string类啊   strcpy(ptr,rhs.ptr);
楼主可以尝试不用这个   自己写个循环就可以搞定   注意 这可是深拷贝哦
1