看板 C_and_CPP 關於我們 聯絡資訊
※ 引述《WanCW (笨狐狸)》之銘言: : ※ 引述《myselves (...)》之銘言: : : 而copy constructor的型態未必要跟class本身一樣 : : 例如 Xxxxx(const Yyyyy &rhs); 是可以的(通常都是Xxxxx(const Xxxxx &rhs);) : : 當 : : Yyyyy y; : : Xxxxx x = y; //這時候 Xxxxx(const Yyyyy &rhs)會被呼叫 : 只有型態完全相同的, 才會被視為 Copy Constructor. Y y1; X x1 = y1; 這種寫法,在「語意」上,是以 y1 為引數,呼叫 X(const Y&) 以產生一個 X 的暫時物件,然後再以這個 X 的暫時物件做引數, 呼叫 X(const X&) 來建構 x1 這個 X 的物件。「語意」上是如此, 但在compiler實作上,C++ 標準容許其做最佳化,呼叫 X(const Y&) 時,就直接建構出 x1, 而不是執行 X(const Y&) 只產生過渡性的 暫時物件,接著再呼叫 X(const X&) 才終於建構出 x1。由於許多 編譯器都有做這種最佳化,因此很容易讓人誤以為只需要有 X(const Y&) 就能寫 X x1 = y1; Anyway,編譯器仍然得要求程式符合需要兩層建構子的「語意」限制, 也就是說,即使是做這種最佳化的編譯器,仍然得先檢查 X(const X&) 這個建構子是不是能夠被存取以執行,否則,就不能通過編譯。例如: class Y {}; class X { public: X() { cout << "X()\n"; } X(const Y&) { cout << "X(const Y&)\n"; } X(const X&) { cout << "X(const X&)\n"; } }; int main() { Y y1; X x1 = y1; } 上述可以通過編譯,並正確執行( <iostream>等等請自己加:)。但是 若動個手腳,將 X(const X&)移到 private: 區,那就不行通過編譯啦。 class Y {}; class X { public: X() { cout << "X()\n"; } X(const Y&) { cout << "X(const Y&)\n"; } private: X(const X&) { cout << "X(const X&)\n"; } }; int main() { Y y1; X x1 = y1; } Comeau compiler 的錯誤訊息說得很清楚: error: "X::X(const X &)" is inaccessible (Even though the copy was eliminated, the standard still requires it to be accessible) X x1 = y1; ^ 這樣就可看出 X(const X&) 對於 X x1 = y1; 這個敘述的必要性了。 當然,若根本不宣告 X(const X&) 的話,compiler 依標準會默默地 (implicitly)幫我們生出一個來,那當然還是可以編譯執行的。 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 220.130.208.168
elsvent:要注意的是有用到pointer就要小心了 61.62.218.129 06/22
※ 編輯: khoguan 來自: 220.130.208.168 (06/23 11:53)