这是我为研究C ++运算符重载而编写的一个简单示例。当我执行它时,代码挂在语句c = a + b;处。并且控制永远不会达到c.display();
作为调试的一部分,如果我在赋值运算符重载函数中放入cout << ptr << '\n';
,它确实会打印出HelloWorld,因此字符串似乎没有格式错误。
那为什么挂呢?我想念什么??
class mystring
{
char *ptr;
public:
mystring(char *str = "")
{
ptr = new char[strlen(str) + 1];
strcpy(ptr,str);
}
mystring operator +(mystring s)
{
char *str = new char[strlen(ptr) + strlen(s.ptr) + 1];//where should this memory be freed
strcpy(str,ptr);
strcat(str,s.ptr);
return mystring(str);
}
void operator =(mystring s)
{
strcpy(ptr,s.ptr);
//cout << ptr << '\n'; \\Debug - this prints out HelloWorld but still hangs
}
void display()
{
cout << ptr << '\n';
}
~mystring()
{
delete [] ptr;
}
};
int main()
{
mystring a="Hello",b="World",c;
c = a + b;
c.display();
getchar();
}
编辑:编译器:MS-Visual C ++ 2010 Express / Windows。
最佳答案
我认为您得到的是内存错误。这行:
c = a + b;
执行以下操作:
c.constructor()
c.operator=(a.operator+(b));
并且您的操作员=无法分配内存
void operator =(mystring s)
{
// ptr is allocated enough memory for "", i.e. one byte
strcpy(ptr,s.ptr); // copying more than one byte into one byte array
//cout << ptr << '\n'; // this works, but you've trashed memory with the strcpy
} // stack might be corrupted here, depends where this is, so execution can end up anywhere
您需要的是:
void operator = (mystring &s) // reference!
{
delete [] ptr;
ptr = new char [strlen (s.ptr + 1)];
strcpy (ptr, s.ptr);
}
关于c++ - 为什么此代码卡在提到的位置?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7390420/