這裏構造/複製構造的問題是一個代碼段:C++以g ++ 3.4.6
class test {
public:
test(){
cout<<"I am in default constructor ";
}
static void func(const test &obj){
cout<<"I am in function ";
}
protected:
test(const test &o){
cout<<"I am in copy constructor ";
}
};
int main()
{
test::func(test());
}
上面的代碼給出了關於彙編使用g ++ 3.4.6(在Red Hat Linux)以下錯誤:
如果你使用g ++ 3.3.2或g ++ 4.4.3或任何其他G ++版本(在Red Hat Linux)編譯In function `int main()':
error: `test::test(const test&)' is protected
error: within this context
然而,編譯成功,並給出以下的輸出:
I am in default constructor I am in function
在上面的代碼中,我已經通過臨時對象(由默認構造函數創建)通過引用來運行func。那麼爲什麼編譯器3.4.6正在調用複製構造函數呢?
複製[爲什麼拷貝構造函數在通過const ref傳遞temp時被調用?](http://stackoverflow.com/questions/4733448/why-copy-constructor-is-called-when-passing-temp-by- const-ref) – 2011-02-03 09:33:05