[英]Using conversion constructor implicitly requires copy constructor
我正在學習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 ++編譯器。
因為:
void testFunction(Test in)
您正在按值傳遞Test
對象,該對象將調用復制構造函數。
該問題的另一種解釋是:
如果從Test
類中刪除復制構造函數Test(const Test&)
,則必須使用編譯器生成的復制構造函數,該構造函數將調用subClass sub
的復制構造函數。 但是您將其定義為subClass(subClass&)
,它與常規不兼容。 因此,如果將其更改為subClass(const subClass&)
,則可以立即刪除Test(const Test&)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.