C++ 在c+中复制构造函数+;带重载运算符()

C++ 在c+中复制构造函数+;带重载运算符(),c++,constructor,operator-overloading,C++,Constructor,Operator Overloading,我试图编写一个简单的代码来理解重载运算符和复制构造函数是如何工作的。但我把它们放在一个地方。这是我的密码 #include <iostream> using namespace std; class Distance { private: int feet; int inches; public: // required constructors Dist

我试图编写一个简单的代码来理解重载运算符和复制构造函数是如何工作的。但我把它们放在一个地方。这是我的密码

 #include <iostream>
 using namespace std;

 class Distance
 {
    private:
       int feet;             
       int inches;           
    public:
       // required constructors
       Distance(){
          feet = 0;
          inches = 0;
       }
       Distance(int f, int i){
          feet = f;
          inches = i;
       }
       Distance(Distance &D){
          cout<<"Copy constructor"<<endl;
          this->feet = D.feet;
          this->inches = D.inches;
       }
       // overload function call
       Distance operator()(int a, int b, int c)
       {
          Distance D;
          // just put random calculation
          D.feet = a + c + 10;
          D.inches = b + c + 100 ;
          return D;
       }

 };
 int main()
 {
    Distance D1(11, 10);
    Distance D2 = D1(10, 10, 10); // invoke operator() why here copy constructor is not called
    return 0;
 }
未调用复制构造函数。它不应该先调用重载运算符,然后再转到复制构造函数吗?为什么会出现错误?

此处:

D2 = D1(10, 10, 10);
D1(10,10,10)
中调用
操作符()
,然后调用
操作符=

如果要调用复制构造函数,需要执行以下操作:

Distance D2(D1);
只是一个提示:看看复制构造函数签名-它准确地显示了您应该如何调用它。

这里:

D2 = D1(10, 10, 10);
D1(10,10,10)
中调用
操作符()
,然后调用
操作符=

如果要调用复制构造函数,需要执行以下操作:

Distance D2(D1);

只是一个提示:看看复制构造函数签名-它确切地显示了您应该如何调用它。

这是因为
D2
已经存在。您已在上面的一行创建了它

Distance D1(11, 10), D2;
                     ^
所以
=
的意思是
操作符=
。对象被分配了新值(这个新值是调用
D1
上的
操作符()(int,int,int)
)而不是使用某些值创建(构造)的

要调用复制构造函数,需要在对象的创建行中为其赋值

int main() {
    Distance D1(11, 10);
    Distance D2( D1);   // calls copy ctor
    Distance D3 = D1;   // calls copy ctor
    return 0;
}
但是


这是因为
D2
已经存在。您已在上面的一行创建了它

Distance D1(11, 10), D2;
                     ^
所以
=
的意思是
操作符=
。对象被分配了新值(这个新值是调用
D1
上的
操作符()(int,int,int)
)而不是使用某些值创建(构造)的

要调用复制构造函数,需要在对象的创建行中为其赋值

int main() {
    Distance D1(11, 10);
    Distance D2( D1);   // calls copy ctor
    Distance D3 = D1;   // calls copy ctor
    return 0;
}
但是


D2=D1使用赋值运算符。对于运算符()使用NRVO,因此也没有副本。D2=D1使用赋值运算符。对于运算符(),使用了NRVO,因此也没有复制。虽然如果执行
距离D2=D1
,它也会复制构造
D2
。尽管执行
距离D2=D1
,它也会复制构造
D2