叫哪个ctor?

时间:2012-05-03 18:27:11

标签: c++ copy-constructor

  

可能重复:
  Why copy constructor is not called in this case?
  What is copy elision and how does it optimize the copy-and-swap idiom?

我正在试图理解ctors和运算符重载。

#include <iostream>
using namespace std;

class number {
   int n;
 public:
   number(int i=0):n(i)     {       cout<<"in ctor"<<endl;    }
    ~number()               {       cout<<"in dtor"<<endl;    }
   number(const number& obj):n(obj.n)   {
                                    cout<<"in copy ctor"<<endl;   }
   number operator+(const number & obj)  {
                                     return number(n+obj.n);   }

    number operator=(const number &rhs)  {
               n = rhs.n;        cout<<"in assignemnt opr"<<endl;    }
   void disp() {cout<<n<<endl;}
};

int main()
{
        number one(1),two(2);
        number three =one + two; //was expecting copy ctor being called here
        three.disp();
}

当我运行上面的代码时,我得到了以下输出

enter image description here

我理解在重载的one运算符中调用了三个构造函数twoun-named+对象。我无法理解three如何我想要复制ctor应该被调用。但它似乎不是。 有人可以解释一下。感谢。

0 个答案:

没有答案