我只是想重载 = 运算符来复制字符串。
class cString
{
int len;
char *mbuff;
};
int main()
{
cString s1,s2;
s1 = s2;
//here s1 goes out of scope and its destructor called
cout<<" hello";
......
......
......
return 0;
}
cString& cString::operator=(const cString &s)
{
if(this->mbuff!=NULL)
delete[] (this->mbuff);
this->len = s.len;
this->mbuff = new char[this->len+1];
strcpy(this->mbuff,s.mbuff);
return *this;
}
s1=s2 被视为s1.operator=(s2);
在operator=函数中,s1 被隐式传递。由于 s1 是在 main 的块中创建的,所以应该在最后调用s1 的析构函数。即就在退出主要之前。
但是如果我写返回类型cString&(reference) s1 的析构函数在从函数返回到 main 后立即被调用。但如果返回类型为void,它不会立即调用 s1 的析构函数。它在退出主程序时正常调用..
为什么当我返回引用时对象s1超出范围?return *this 的确切含义是什么?
我知道没有必要返回参考。我已经使用 void 返回类型成功执行了我的代码。我只是好奇会发生什么……!
谢谢...!