c++ - 使用重载运算符 () 在 C++ 中复制构造函数

标签 c++ constructor operator-overloading

我尝试编写一个简单的代码来理解重载运算符和复制构造函数的工作原理。但是我堆在一个地方。这是我的代码

 #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;
 }

我的问题是:为什么在这行 main

Distance D2 = D1(10, 10, 10); // invoke operator() why here copy constructor is not called

不调用复制构造函数。它不应该首先调用重载运算符然后再去复制构造函数吗?为什么会报错?

最佳答案

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

Distance D1(11, 10), D2;
                     ^

所以=的意思就是operator=。该对象被分配 新值(这个新值来自 D1 上对 operator() ( int, int, int) 的调用)并且没有创建(构造)具有某些值(value)。

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

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

但是

int main() {
    Distance D1(11, 10);
    Distance D2;
    D2 = D1;   // calls operator=
    return 0;
}

关于c++ - 使用重载运算符 () 在 C++ 中复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23608696/

相关文章:

c++ - 我应该 'delete' 这个 CDC 吗?

java - 当构造函数需要调用可重写方法时保持干燥

java - 当我们尝试使用 'new' 创建原始数组对象时会调用哪个类构造函数

c++ - 为什么下面的代码段返回指针所指向的值而不是指针的地址?

c++ - 重载一元运算符 & 是否有意义?

c++ - 如何在不包含 "using namespace std"的情况下在代码中使用 std?

c++ - 如何在构造函数中初始化 "ostream &out",使用 "char *filename"

c++ - 如何在基类中实现子类迭代器的统一接口(interface)?

c++ - 媒体基金会 AMR 解码

inheritance - 如何在子类中将多个父类构造函数与 val 混合