【发布时间】:2011-11-03 02:03:11
【问题描述】:
我正在学习 C++,但遇到了一些奇怪的事情,我在我的 C++ 书籍或网络上找不到任何信息。下面的代码只是对转换构造函数的测试:Test(int)。 testFunction 在需要 Test 对象的地方获得一个 int,并且转换构造函数用于创建一个 Test 对象以发送到函数。这按预期工作。
#include <iostream>
using namespace std;
class subClass {
public:
subClass(int);
subClass(subClass&);
};
subClass::subClass(int i) {};
subClass::subClass(subClass& i) {};
class Test {
public:
Test(const Test&);
Test(int);
subClass sub;
};
Test::Test(const Test &)
: sub(1) {};
Test::Test(int in)
: sub(1) {};
void testFunction(Test in) {
cout << "testfunction\n";
};
int main () {
testFunction(4);
}
但是,如果我从 Test 类中删除复制构造函数 Test(const Test&),则会收到如下所示的错误消息。但是从不使用复制构造函数,那么为什么需要它呢?
example.cpp: In function `int main()':
example.cpp:32: error: no matching function for call to `Test::Test(Test)'
example.cpp:13: note: candidates are: Test::Test(Test&)
example.cpp:24: note: Test::Test(int)
example.cpp:32: error: initializing argument 1 of `void testFunction(Test)' from result of `Test::Test(int)'
附加信息: 我注意到,无论是从子类中删除复制构造函数还是通过引用 testFunction 传递参数,都可以在没有 Test 的复制构造函数的情况下编译函数。我在 cygwin 中使用 gnu g++ 编译器。
【问题讨论】:
标签: c++ constructor copy-constructor