c++ - 从未使用过转换为基类

标签 c++ c++11 base-class explicit typecast-operator

我有两个类,一个是从另一个类私有(private)派生的(因为我不想公开基础的接口(interface))。不过稍后我想创建对基础的引用。

我可以使用普通成员函数 base() 来完成此操作,但不能使用强制转换运算符来完成此操作,因为从未调用此运算符

clang 对此发出警告,因为它说“它永远不会被调用”。

为什么强制转换运算符会被忽略并被私有(private)元素覆盖? 这是语言不一致吗?

实际上,我认为它有一个公开的基本引用,仅此而已。 更重要的是,如果它有效,它可能是显式的

class A{
    int v_;
public:
    void f(){}
};

class B : A{ // A is private base because I don't want the f() interface
    int w_;
public:
    A const& base() const{return *this;}
    /*explicit*/ operator A const&() const{return *this;} // never called, warning in clang
};

int main(){
    A a = {};
    B b = {};
    A const& a2 = b.base();
    A const& a3 = b; // bad, But why?
    A const& a4{b}; // explict doesn't help
    A const& a5 = b.operator A const&(); // works in clang (but with a contradictory warning), doesn't work with gcc
}

最佳答案

a3a4 情况下,您正在使用左值初始化引用。在这种情况下,如果引用的类型是初始化器类型的基类,则引用直接绑定(bind)到初始化器,不涉及任何转换 (C++17 [dcl.init.ref]/5)。

由于基类不可访问,因此程序格式错误 (dcl.init.ref/4)。

我不确定 a5 中的访问检查规则,尽管它在实践中似乎没有实际意义,因为您不会设计代码,以便有人必须编写该语法。

另请参阅[class.conv.fct]/1:

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.

关于c++ - 从未使用过转换为基类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52195809/

相关文章:

c++ - 我们什么时候需要在#undef 之前使用#ifdef?

c++ - 将元素插入 vector 时避免复制参数

c++ - 静态构建 Windows 应用程序时出错

c++ - std::stack 如何组织内部存储?

c++ - 运算符按位左移

c++ - std::thread 从线程函数内部释放

c++ - 了解虚拟基类和构造函数调用

c# - 如何在基类上调用显式实现的接口(interface)方法

c++ - 专用内部类模板函数的类外定义?

c++ - 在 C++ 的函数调用中完成强制转换是否真的有效?