访问基类中直接受保护的字段

Access directly protected field in a base class

本文关键字:受保护 字段 基类 访问      更新时间:2023-10-16

以下代码:

#include <iostream>
using namespace std;
class Base {
protected :
int a;
public :
Base() {};
Base(int x) :a(x) {};
};
class Derived : public Base {
public:
Derived(int x) : Base(x) {};
};

int main() {
Derived b(11);
int x;
x=b.a;
}


不编译,因为"int Base::a">在此上下文中受到保护。

我知道派生类无法访问其他Base实例的成员。

我阅读了以下帖子访问派生类中的受保护成员(以及其他相关帖子(。所以我尝试不同的东西。例如,我为派生类添加了一个新的构造函数。

Derived() {Base(static_cast<Derived*>(this)->a);};

但是,正如预期的那样,没有成功。是否有直接访问类保护字段Base(a字段中必须protectedBase(的方法(某些修饰符或其他东西(?


您可以使用using指令覆盖访问说明符

#include <iostream>
using namespace std;
class Base {
protected :
int a;
public :
Base() {};
Base(int x) :a(x) {};
};
class Derived : public Base {
public:
Derived(int x) : Base(x) {};
using Base::a;
};

int main() {
Derived b(11);
int x;
x=b.a;
}