我有一個類層次結構,可以簡單地把這樣接受家長參考:有一個子類的構造函數
struct Parent {
Parent() { }
Parent(Parent& p, std::string s) { }
private:
// I want this class to be non-copyable
Parent(const Parent&);
};
struct Child : public Parent {
Child() { }
Child(Parent& p) : Parent(p, "hi") { }
};
當我試圖創建兩種情況是這樣的:
Child c1;
Child c2(c1);
我從鏘出現以下錯誤:
test.cpp:37:8: error: call to deleted constructor of 'Child'
Child c2(c1);
^~~
test.cpp:30:8: note: function has been explicitly marked deleted here
struct Child : public Parent {
^
1 error generated.
我想這個類是不可複製的,那麼有沒有辦法到h大小寫Parent&
重載而不是複製構造函數?我知道爲什麼它的行爲如此,但我正在尋找解決方法。我想要Child(Parent& p)
而不必施放它。
我在GCC和Visual Studio中也出現這個錯誤。儘管如此,英特爾的編譯器並沒有得到它,但其他三個廠商的一致行爲似乎表明這是錯誤的,其他的都是正確的。
那麼你是要求解決方法還是爲什麼它不起作用? – ildjarn 2012-03-16 01:35:02
@ildjarn我知道它爲什麼不起作用,我需要一個解決方法。對不起,我會編輯它以使其更清楚。 – 2012-03-16 01:36:45
當傳遞一個符合cv資格的'Child&'時,根本沒有辦法使構造函數具有比複製構造函數更高的過載優先級。你需要去鑄造,輸入擦除,工廠函數而不是公共構造函數或靜態多態性。 – ildjarn 2012-03-16 01:45:46