相关疑难解决方法(0)

为什么复制赋值运算符必须返回引用/ const引用?

在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

62
推荐指数
4
解决办法
4万
查看次数

Operator =在C++中重载

在C++ Primer一书中,它有一个C风格字符数组的代码,并展示了如何=在第15.3Operator =中重载运算.

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)

c++ string operator-overloading visual-c++

11
推荐指数
2
解决办法
1222
查看次数