gpt4 book ai didi

C++:为什么无法在派生类中访问 protected 构造函数?

转载 作者:行者123 更新时间:2023-12-01 14:36:41 28 4
gpt4 key购买 nike

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

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();
}

我注意到有一个相关的帖子,但是那里的类是一个模板类。我的只是一个“常规”类(class)。

Why the derived class cannot access protected base class members?

最佳答案

protected members可以从派生类访问,但只能通过派生类访问。

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:

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

换句话说,当前派生类实例的protected成员可以访问,而独立基类的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
}
};

关于C++:为什么无法在派生类中访问 protected 构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62688978/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com