为什么不使用私人基地的演员表运营商?

Why does the cast operator to a private base not get used?

在此代码中,分配给 b1 有效,但不允许分配给 b2(有或没有静态转换)。我实际上是在尝试解决相反的问题,public 继承但不隐式转换为基础。但是,似乎从未使用过 cast 运算符。这是为什么?

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]

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.

所以在你的第一个例子中:

struct D1 : private B {
    operator B&() {return *this;}
    B& getB() {return *this;}
};

operator B& 将永远不会被使用,因为它转换为基数 class。就算是私人基地也没关系class。