[英]Why does the cast operator to a private base not get used?
在此代碼中,分配給b1有效,但它不允許分配給b2(有或沒有靜態強制轉換)。 我實際上試圖解決相反的問題,公共繼承但不是隱式轉換為基礎。 然而似乎從未使用過演員。 為什么是這樣?
struct B {};
struct D1 : private B {
operator B&() {return *this;}
B& getB() {return *this;}
};
struct D2 : public B {
explicit operator B&() {return *this;}
};
struct D3 : public B {
operator B&() = delete;
};
void funB(B& b){}
int main () {
D1 d1;
funB(d1.getB()); // works
// funB(d1); // fails to compile with 'inaccessible base class
D2 d2;
funB(d2); // works
D3 d3;
funB(d3); // works
return 0;
}
來自[class.conv.fct] :
轉換函數從不用於將(可能是cv限定的)對象轉換為(可能是cv限定的)相同的對象類型(或對它的引用), 轉換為該類型的(可能是cv限定的)基類(或引用它)或(可能是cv-qualified)void。
所以在你的第一個例子中:
struct D1 : private B {
operator B&() {return *this;}
B& getB() {return *this;}
};
operator B&
永遠不會被使用,因為它轉換為基類。 它是一個私人基類並不重要。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.