繁体   English   中英

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

[英]Copy constructor in c++ with overloading operator ()

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

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

我的问题是:为什么在这一主要方面

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

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

这里:

D2 = D1(10, 10, 10);

您在D1(10, 10, 10) operator()中调用operator() ,然后又调用operator=

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

Distance D2(D1);

提示:看一下复制构造函数签名-它准确显示了您应该如何调用它。

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

Distance D1(11, 10), D2;
                     ^

因此=的含义是operator= 该对象被分配了一个新值(此新值是通过调用D1上的operator() ( int, int, int)产生的 ),而不是使用某些值创建 (构造)的。

要调用复制构造函数,您需要在其创建行中为对象分配一个值

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM