【发布时间】:2017-12-06 15:54:24
【问题描述】:
我有以下 c++ 代码(VS2013):
#include <iostream>
using namespace std;
class A {
int i;
public:
A(int i) : i(i) {
cout << "Constructor: " << i << endl;
}
A(const A &o) : i(o.i) {
cout << "Copy constructor: " << i << endl;
}
~A() {
cout << "Destructor: " << i << endl;
}
};
A test(const A &a, A b, A *c) {
return *c;
}
int main() {
A b(10);
cout << "START OF TEST" << endl;
test(1, b, &b);
cout << "END OF TEST" << endl;
system("pause");
}
运行代码时,我在“测试开始”和“测试结束”输出之间得到以下输出:
构造函数:1
复制构造函数:10
复制构造函数:10
析构函数:10
析构函数:10
析构函数:1
构建了 3 个对象:1 个使用整数 1,2 个使用 A 类的对象(i = 10)。
值得一提的是,当test函数的参数const A &a改为A &a(不是常量)时,程序无法编译,报错如下:
错误 C2664: 'A test(A &,A,A *)' : 无法将参数 1 从 'int' 到 'A &'
如何解释这种行为?
具体来说:
为什么将整数
1发送到test会使A 的参数构造函数A(int i)工作(并且仅在使用const时)?为什么 A 的复制构造函数 A(const A &o) 工作两次? (调用
test时发生一次运行,返回*c时发生另一次运行)。
【问题讨论】:
-
i(i)shudder。请少用大胆的命名... -
@Gil 你回答第二个问题了吗?
标签: c++ constructor type-conversion copy-constructor