我尝试编写一个简单的代码来理解重载运算符和复制构造函数的工作原理。但是我堆在一个地方。这是我的代码
#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/