【发布时间】:2015-08-09 20:53:36
【问题描述】:
我试图理解 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+ 函数按值返回。
【问题讨论】:
-
为什么用代码格式标记“复制构造函数”?很奇怪。
-
我试图观察这些函数是如何被调用的。
-
不,我的意思是,在您的问题正文中。我会改正的。
标签: c++ operator-overloading copy-constructor