由于复制构造函数导致的编译错误

时间:2012-03-30 08:25:35

标签: c++

#include<iostream>

using namespace std;

class Abc
{
        public:

        int a;

        Abc()
        {
    cout<<"Def cstr called\n";
                a=0;
        }


        Abc(Abc &source)
        {
                a=source.a;
                cout<<"copy constructor is called"<<endl;
        }
        void operator = (Abc &source)
        {
                a=source.a;
                cout<<"overloaded assignment operator"<<endl;
        }
        Abc display(Abc ab)
        {
                cout<<"The a in display "<<ab.a<<endl;
                return ab;
        }
};

int main()

{

        Abc a;

        Abc b;

        a.a=10;

        b=a;

        cout<<"b.a ="<<b.a<<endl;

        Abc x;

        x = (a.display(b));

        return 0;

}

在x =(a.display(b))行中,我收到了编译错误。在评论这条线时它起作用。请帮助修改程序,以便成功编译它,请告诉我这里有什么问题。

4 个答案:

答案 0 :(得分:1)

您应该通过const引用传递构造函数和赋值参数,而不仅仅是通过引用:

即:

Abc(const Abc &source) { ... }
const Abc& operator=(const Abc &source) { ... }

可能(或可能不)也希望显示如下:

const Abc& display(const Abc &ab)
{
        cout<<"The a in display "<<ab.a<<endl;
        return ab;
}

ASIDE:虽然这些更改并非严格要求,但它们可以防止一些棘手的错误 - 其中一个是您遇到的:

void operator = (Abc &source);
Abc display(Abc ab);

Abc a, b, x;

x = (a.display(b));

此处显示正在返回临时Abc,而operator=正在使用非常量Abc引用。 C ++的一个奇怪的规则是你不能将非const引用绑定到临时 - 因此你的错误。

答案 1 :(得分:1)

编译器引发错误,因为将临时对象分配给非const引用是非法的。在这种情况下,临时是由Abc返回的a.display()对象,然后传递给赋值运算符。

创建复制构造函数和赋值运算符const的参数:

Abc(const Abc& source) { .. }
void operator=(const Abc& source) { ... }

注意,赋值运算符通常会防止自我赋值并返回对自身的引用:

Abc& operator=(const Abc& source)
{
    if (this != &source)
    {
        a = a.source; 
    }
    return *this;
}

答案 2 :(得分:1)

您的operator=不会返回任何内容。一开始可能看起来不太直观,但您需要返回*this的引用,这样就可以让您执行a = b = c之类的操作。

const Abc & operator = (const Abc &source)
{
    a=source.a;
    cout<<"overloaded assignment operator"<<endl;
    return *this;
}

此外,惯例是使用const引用(因为您不希望更改复制构造函数中的原始对象或operator=)。

Abc(const Abc &source) { ... }
...
Abc & display(Abc &ab) { ... }

我也更改了display的返回类型和参数。基本上,尽可能使用引用。因为你返回的是作为参数传递的相同内容,所以可以这样做。如果你在函数内创建一个新对象(但在堆栈上,而不是字面上使用new),你必须返回一个值。

答案 3 :(得分:1)

我们不确定您收到的错误消息我的建议很少

//Make the parameter as constant
           Abc(const Abc &source)
            {
                    this.a=source.a;
                    cout<<"copy constructor is called"<<endl;
            }
//change the return type
            ABC& operator = (const Abc &source)
            {
                  cout<<"overloaded assignment operator"<<endl;
                    if (this == &source)
                          return *this;
                    this.a=source.a;
                     **// return the existing object**
                   return *this;  
            }