#include <iostream>
class A {
public:
A(){ cerr << "A Constructor" << endl; }
~A(){ cerr << "A Destructor" << endl; }
A(const A &o){ cerr << "A Copy" << endl; }
A& operator=(const A &o){ cerr << "A Assignment" << endl; return *this; }
};
class B : public A {
public:
B() : A() { cerr << "B Constructor" << endl; }
~B(){ cerr << "B Destructor" << endl; }
private:
B(const B &o) : A() { cerr << "B Copy" << endl; }
B& operator=(const B &o){ cerr << "B Assignment" << endl; return *this; }
};
int main() {
A a;
const A &b = B();
return 0;
}
在GCC 4.2,我得到這個消息:意外const引用行爲
In function 'int main()':
Line 16: error: 'B::B(const B&)' is private
compilation terminated due to -Wfatal-errors.
如果我刪除了 「私人」 從B,我得到的輸出我想到:
A Constructor
A Constructor
B Constructor
B Destructor
A Destructor
A Destructor
我的問題是:爲什麼要製作一個不被稱爲private的方法,無論這個代碼是否編譯?這是標準授權嗎?有沒有解決方法?
我不明白爲什麼這不應該編譯。 FWIW,Comeau與我同意。 – sbi 2010-07-14 18:22:34
@sbi:奇怪的是,Comeau拒絕禁用C++ 0x擴展的代碼,但接受啓用了C++ 0x擴展的代碼。 – 2010-07-14 18:23:26
g ++ 4.4.2,FWIW沒有錯誤。 – 2010-07-14 18:44:20