简体   繁体   English

为什么不使用私人基地的演员?

[英]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.

相关问题 为什么我的模板运算符==不被使用? - Why does my templated operator== not get used? 为什么运算符新功能需要强制转换 - why does operator new function need cast 私有基础中的类型转换运算符 - typecast operator in private base 为什么dynamic_cast在这里为nullptr提供私有继承? - Why does dynamic_cast give nullptr with private inheritance here? 为什么reinterpret_cast在私人继承中确实起作用 - Why reinterpret_cast does work in private inhertiance 为什么static_cast不使用转换运算符指向const? - Why does static_cast not use the conversion operator to pointer to const? 为什么lexical_cast要求operator >>在匹配的命名空间中? - Why does lexical_cast require the operator>> to be in a matching namespace? 为什么在虚函数中转换为Base类会产生分段错误? - Why does this cast to Base class in virtual function give a segmentation fault? 为什么static_cast(* this)到基类创建临时副本? - Why does static_cast(*this) to a base class create a temporary copy? 为什么我的重载转换运算符无法访问私有成员? - Why does my overloaded casting operator not have access to private members?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM