2011-02-03 67 views
2

這裏構造/複製構造的問題是一個代碼段: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正在調用複製構造函數呢?

+1

複製[爲什麼拷貝構造函數在通過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

回答

0

很可能是因爲舊的g ++版本(我相信它代表了其他編譯​​器)並不完全符合C++標準,並且在當前版本中存在更多的錯誤。正如你所說,這個版本可以在更高版本上運行,因此它很可能是固定的。

編輯

順便說一下,你有沒有試圖改變編譯器設置?不同的優化級別可能有不同的錯誤。

+2

http://stackoverflow.com/questions/4733448/why-copy-constructor-is-called-when-passing-temp-by-const-ref - 這不是一個錯誤。它符合標準。這個行爲在GCC中被改變了,因爲它有點愚蠢,而且語言本身使用C++ 0x修復它。 – 2011-02-03 09:37:24