<分区>
我想了解 C++ 中复制构造函数的概念。我编写了以下程序:
#include<iostream>
using namespace std;
class Box{
private:
int d;
public:
Box(int i){
cout << "Constructor" << endl;
d = i;
}
Box(const Box &old){
cout << "Copy Constructor" << endl;
d = old.d;
}
int getd(){
return d;
}
~Box(){
cout << "Destructor" << endl;
}
Box operator+(const Box& op){
Box c(15);
c.d = d + op.d;
return c;
}
};
int main(){
Box a(10);
Box b = a;
Box c = a+b;
cout << c.getd() << endl;
return 0;
}
这个程序的输出如下:
Constructor
Copy Constructor
Constructor
20
Destructor
Destructor
Destructor
我不明白为什么没有在 main
函数的第三行调用复制构造函数。我认为应该调用复制构造函数,因为 operator+
函数按值返回。