当前位置: 首页 > >

实现string类= + ==运算符重载

发布时间:

#include
#include
usring namespace std;
class String{
public:
String (char *str = NULL)
{
this->ptr = new char[strlen(this->ptr) + 1]; //在堆区开辟空间
strcpy (this->ptr, str); //将str指针指向的字符串拷贝到ptr指针指向的空间

}
~String()
{
delete [] (this->ptr); //释放开辟的空间
}
public:
char *getaddr() const
{
return (this->ptr);
}
String operator + (String &);
String operator = (const String&);
int operator == (String &);
private:
char *ptr; //保存堆区开辟空间的首地址
};
//实现+运算符重载
String String::operator + (String &obj)
{
int len = strlen(this->ptr) + strlen(obj.ptr) + 1; //得到两个字符串的长度之和
char *p = new char[len]; //开辟一个新的空间用来存放连接后的两个字符串
strcpy (p, this->ptr);
strcat (p, obj->ptr);
String tmp(p); //构造一个临时的对象
cout << &tmp << endl;
delete [] p;
return tmp;
}
//实现=运算符重载
String String:: operator =(const String &obj)
{
delete this->ptr; //释放对象原先的空间
this->ptr = new char[strlen(obj.prt) + 1]; //开辟一个新的堆区空间,大小与obj.ptr指针指向的字符串的空间大小一样
strcpy(this->ptr, obj.ptr);
return (*this);
}
//实现==运算符重载
int String:: operator == (String &obj)
{
return strcmp(this->ptr, obj.ptr);
}

int main()
{
String a = "hello ";
String b = "world";
String c = a + b;
cout << c.getaddr() << endl;
cout << (a == b) << endl;
a = b;
cout << a.getaddr() << endl;
}



友情链接: