C++:为什么在 Derived Class 中无法访问受保护的构造函数?

C++: Why Protected Constructor Cannot be Accessed in the Derived Class?

受保护的成员应该可以从派生 class 访问。 那么,为什么我在下面的代码中会出现编译错误?

class A {
protected:
    A() {};
};

class B : public A {
public:
    void g() { 
        A a; // <--- compiling error: "Protected function A::A() is not accessible ...". Why?
    }
};


int main() {
    B b;
    b.g();
}

我注意到有一个相关的 post,但是 class 有一个模板 class。我的只是一个“普通” class.

Why the derived class cannot access protected base class members?

protected members 可以从派生 class 访问,但只有通过派生 class.

A protected member of a class is only accessible

  1. ...
  2. to the members and friends (until C++17) of any derived class of that class, but only when the class of the object through which the protected member is accessed is that derived class or a derived class of that derived class:

因此即使在派生class的成员函数中也不能创建基class的独立对象。

换句话说,派生class的当前实例的protected个成员可以访问,但是独立基class的protected个成员不能'吨。例如

class A {
protected:
    int x;
public:
    A() : x(0) {}
};

class B : public A {
public:
    void g() {
        this->x = 42; // fine. access protected member through derived class
        A a;
        a.x = 42;     // error. access protected member through base class
    }
};

Protected member is supposed to be accessible from derived class.

是的,但仅当通过 this 指针访问时。在一个完整的独立对象上访问时不是。当 B::g() 试图构造一个新的 A 对象时,您正在尝试这样做。