c++ - 有什么方法可以通过 using 声明来提高可见度吗?

标签 c++

以下代码无法编译:

class C
{
    private:

        int m_x;

    protected:

        C(int t_x) : m_x(t_x) { }

};

class D : public C
{
    public:

        using C::C;

};

int main(int argc, char **argv)
{
  D o(0);
}

编译器反对 C 的构造函数被声明为 protected,这意味着我无法从 main 访问它。换句话说,似乎 using 声明拖拽了标识符的原始可见性,尽管它存在于 public block 中。

两个问题:

  1. 为什么会这样? (无论是关于其运作方式的规则,还是制定这些规则的理由)。
  2. 有什么方法可以解决这个问题而无需显式地为 D 编写构造函数?

最佳答案

这是一个微妙的问题。在 C++ 中,在基类构造函数上使用 using 关键字称为继承构造函数,其工作方式与 using 关键字通常的作用不同。具体来说,请注意

If overload resolution selects an inherited constructor, it is accessible if it would be accessible when used to construct an object of the corresponding base class: the accessibility of the using-declaration that introduced it is ignored.

(强调我的。Source)

换句话说,您在 public 部分中包含 using 声明这一事实实际上并没有使这些构造函数公开。

我相信,在这种情况下,您可能必须定义自己的构造函数以匹配基类型构造函数。

关于c++ - 有什么方法可以通过 using 声明来提高可见度吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56777176/

相关文章:

c++ - 在 C++ 中执行此操作的更好方法?标准::字符串

c++ - 获取系统信息 UWP

C++ sublime text插件代码导航

c++ - 无法将模板类定义与 Visual Studio 2010 上的主程序链接

c++ - 错误 : Variable "BOOL" is not a type name

c++ - 获取显卡型号?

c++ - 开发跨平台 C++11 代码

c++ - 将 C++ 程序转换为 Windows 服务?

c++ - 为什么正则表达式 "([a-z])((?!\\1)[a-z])"会匹配 C++11 中的字符串 "aa"?

c++运算符有歧义等