#include <iostream>
using namespace std;
class X
{
public:
X() { cout<<"default constructor"<<endl; }
X(const X&) { cout<<"copy constructor"<<endl; }
};
X test(X a)
{
X y = a;
return y;
}
int main()
{
X obj;
X obj1 = test(obj);
return 0;
}
輸出:拷貝構造函數叫錯
default constructor
copy constructor
copy constructor
我已經編譯使用MinGW的編譯器。
但是,我認爲輸出是錯誤的。 複製構造函數在對象按值傳遞,按值返回或顯式複製時調用。 在上面的程序中,"copy constructor"
必須被調用4次。
test(obj)
被調用,以obj
複製到a
X y = a
被調用時,明確地複製。return y
叫,y
被複制到一個臨時對象,讓它成爲temp
X obj1 = temp
,明確地複製。
請糾正我。提供您的理由太..
如果合適,請添加語言標籤。你還會得到自動的語法高亮;) – dyp