关于等号运算符的重载
代码如下:
#include <iostream>
using namespace std;
class CString
{
public:
CString(char *m="");
~CString();
bool operator ==(const CString &b);
private:
char *str;
};
bool CString::operator ==(const CString &b)
{
char *p,*q;
p=str;
q=b.str;
while (p!='\0'||q!='\0') //在这里如何判断字符串结束的标志?即如何退出循环?我这里写的条件陷入了死循环。
{
if (*p==*q)
{
p++;
q++;
}
else
return false;
}
return true;
}
CString::CString(char *m)
{
str=new char[strlen(m)+1];
if (str==NULL)
{
cerr<<"error";
exit(1);
}
strcpy(str,m);
}
CString::~CString()
{
delete []str;
}
void main()
{
CString s1("abc"),s2("abc");
if (s1==s2)
cout<<"true"<<endl;
else
cout<<"false"<<endl;
}
而且测试的结果是false,显然是错的。