c++ - 为什么使用声明生成的构造函数具有与基类相同的访问级别?

标签 c++ c++14

用代码更容易解​​释:

   class A {
    protected:
        A(int i) {}
        void foo() {}
    };

    class B : public A {
    public:
        B() : A(0) {}
        using A::A;
        using A::foo;
    };

    int main() 
    {
        B b1;
        // [protected] A::foo => [public] B::foo
        b1.foo(); // Ok
        // [protected] A::A(int) => [protected] B::B(int)
        B b2(0); // cannot access protected member
    }

我在 VS2015 中尝试了代码。我可以使用 using 声明更改成员函数的访问级别,但我不能对构造函数执行相同的操作。这对我来说很奇怪。有谁知道为什么他们设计成这样?

最佳答案

在这种情况下不会生成构造函数,而是继承它们(实际上是从基类)。
根据documentation ,当继承一个构造函数时:

It has the same access as the corresponding base constructor

access 表示 access specifiers .
另一方面,对于成员方法:

Using-declaration introduces a member of a base class into the derived class definition, such as to expose a protected member of base as public member of derived.

在这种情况下,可以显式更改访问权限。

这就是为什么您可以使用 using 声明更改成员函数的访问级别,而您不能对构造函数执行相同的操作

关于c++ - 为什么使用声明生成的构造函数具有与基类相同的访问级别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36671798/

相关文章:

c++ - "const"有什么用?

C++ 如何给抽象类中的成员变量一个默认值?

c++ - 调用参数多于参数的函数/仿函数

c++ - 段。由指向结构指针的 vector 的指针引起的退出错误

c++ - 在递归函数中释放内存时堆损坏

c++ - 我的 fstream 总是返回 true,即使文件名错误?

c++ - 为什么我的函数模板特化被 VS2017 拒绝而不是被 VS2015 拒绝?

c++ - 按值传递的整数常量,视为 constexpr?

c++ - sso 是否用于 std::string 以外的任何其他标准库容器?

c++ - 整数匹配正则表达式模式不起作用