在C++中,我不清楚从复制赋值运算符返回引用的概念.为什么复制赋值运算符不能返回新对象的副本?另外,如果我上课A,还有以下内容:
A a1(param);
A a2 = a1;
A a3;
a3 = a2; //<--- this is the problematic line
Run Code Online (Sandbox Code Playgroud)
的operator=定义如下:
A A::operator=(const A& a)
{
if (this == &a)
{
return *this;
}
param = a.param;
return *this;
}
Run Code Online (Sandbox Code Playgroud) c++ operator-overloading copy-constructor assignment-operator
在C++ Primer一书中,它有一个C风格字符数组的代码,并展示了如何=在第15.3条Operator =中重载运算符.
String& String::operator=( const char *sobj )
{
// sobj is the null pointer,
if ( ! sobj ) {
_size = 0;
delete[] _string;
_string = 0;
}
else {
_size = strlen( sobj );
delete[] _string;
_string = new char[ _size + 1 ];
strcpy( _string, sobj );
}
return *this;
}
Run Code Online (Sandbox Code Playgroud)
现在我想知道为什么String &在下面的代码执行相同的工作时需要返回引用,没有任何问题:
void String::operator=( const char *sobj )
{
// sobj is the null …Run Code Online (Sandbox Code Playgroud)