[英]Why does the cast operator to a private base not get used?
In this code assigning to b1 works, but it won't allow assigning to b2 (with or without the static cast). 在此代码中,分配给b1有效,但它不允许分配给b2(有或没有静态强制转换)。 I was actually trying to solve the opposite problem, public inheritance but not implicitly converting to the base.
我实际上试图解决相反的问题,公共继承但不是隐式转换为基础。 However the cast operator never seems to be used.
然而似乎从未使用过演员。 Why is this?
为什么是这样?
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;
}
From [class.conv.fct] : 来自[class.conv.fct] :
A conversion function is never used to convert a (possibly cv-qualified) object to the (possibly cv-qualified) same object type (or a reference to it), to a (possibly cv-qualified) base class of that type (or a reference to it) , or to (possibly cv-qualified) void.
转换函数从不用于将(可能是cv限定的)对象转换为(可能是cv限定的)相同的对象类型(或对它的引用), 转换为该类型的(可能是cv限定的)基类(或引用它)或(可能是cv-qualified)void。
So in your first example: 所以在你的第一个例子中:
struct D1 : private B {
operator B&() {return *this;}
B& getB() {return *this;}
};
operator B&
will never be used because it converts to a base class. operator B&
永远不会被使用,因为它转换为基类。 It doesn't matter that it's a private base class. 它是一个私人基类并不重要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.