求助,关于重载运算符
重载运算符+,=,==,实现字符串连接,字符串的拷贝赋值,字符串的判断相等
#include <iostream.h>
#include <string.h>
class string
{
char* ptr;
public:
string();
string(char* s);
virtual ~string();
void print();
string& operator = (const string& s);
string operator + (string& s2);
bool operator == (string& s2);
};
string::string()
{
}
string::string(char* s)
{
ptr = new char[strlen(s)+1];
strcpy(ptr,s);
}
void string::print()
{
cout << ptr << endl;
}
string::~string()
{
delete ptr;
}
string& string::operator = (const string& s)
{
if ( this == &s)
{
return *this;
}
delete ptr;
ptr = new char[strlen(s.ptr)+1];
strcpy(ptr,s.ptr);
return *this;
}
string string::operator + (string& s2)
{
if (s2.ptr == NULL)
{
return *this;
}
char *p = NULL;
p = new char[strlen(ptr)+strlen(s2.ptr)+1];
while ( *ptr != '\0' )
{
*p++ = *ptr++;
}
while ( *s2.ptr != '\0' )
{
*p++ = *s2.ptr++;
}
p = '\0';
delete ptr;
ptr = new char[strlen(p)];
strcpy(ptr,p);
return *this;
}
bool string::operator == (string& s2)
{
if ( strcmp(ptr,s2.ptr) == 0 )
{
return true;
}
else
return false;
}
void main()
{
string p1("book");
{
string p2("pen");
cout << "p2 ";
p2.print();
p2 = p1;
cout << "p2 ";
p2.print();
}
cout << "p1 ";
p1.print();
string p3("china");
p3 = p3 + p1;
if ( p1 == p3 )
{
cout << "p1与p3一致" << endl;
}
else
{
cout << "p1与p3不一致" << endl;
}
}