复制构造函数调用缺失

时间:2017-08-27 16:51:36

标签: c++ copy-constructor overloading

下面是我试图通过复制构造函数和=运算符重载来解决的代码。 下面我评论了复制构造函数ambguity。

代码:

using namespace std;

class A{
        int a;
    public:
        A(int x = 0){a=x; cout<<"Called ctor for"<<a<<endl;}
        A(const A &obj){cout<<"Copy Ctor called"<<endl;a = obj.a;}
        void set(int x){a=x;}
        int get(){return a;}
        A operator+(const A &);
        A operator*(const A &);
        void operator=(const A &);
};

A A::operator +(const A &obj){
    cout<<"Inside + operator"<<endl;
    return a + obj.a;
}

A A::operator *(const A &obj){
    cout<<"Inside * operator"<<endl;
    return a * obj.a;
}

void A::operator =(const A &obj){
    a = obj.a;
    cout<<"= operator is called"<<endl;
}

int main(){
    A a(10), b(11);
    A c = a + b;    // Why isn't copy ctor is called for this statement?
    c = a+b;
    cout<<"Value: "<<c.get()<<endl;
    cout<<"Value: "<<(a*b).get()<<endl;
    return 0;
}

输出:

Called ctor for10
Called ctor for11
Inside + operator
Called ctor for21  //Just ctor of the temp object from the operator+ () called.
Inside + operator
Called ctor for21
= operator is called
Value: 21
Inside * operator
Called ctor for110
Value: 110

请解释为什么在这种情况下没有调用复制构造函数?

0 个答案:

没有答案