访问基类中直接受保护的字段
Access directly protected field in a base class
以下代码:
#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
字段中必须protected
Base
(的方法(某些修饰符或其他东西(?
您可以使用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;
}
相关文章:
- C++:无法访问声明的受保护成员
- 将结构字段的类型展开为可变模板参数
- 将位字段导出到数组
- 为了方便起见,我应该避免公开私有字段变量吗
- 当字段可以为null时,如何使用C++接口在Avro中写入数据
- 在java中读取c++字节的位字段
- 链接器找不到在虚拟类 c++ 中访问的静态字段的符号
- 私有字段对象与私有继承?
- 继承和友元函数,从基类访问受保护的成员
- 声明没有默认构造函数的字段
- C++内存模型和位字段的最大序列
- 为什么派生类的好友不能使用受保护的成员?
- C++:为什么无法在派生类中访问受保护的构造函数?
- 声明为无效的变量或字段'...' Ardunio 编译器上的错误
- 如何在QByteArray中放置和检索位字段而不会感到痛苦?
- C++ win32 如何使密码字段可选并启用复制和粘贴?
- 何时在抽象类 cpp 中声明受保护的字段
- 访问基类中直接受保护的字段
- C++运算符重载和受保护字段
- 受保护字段的细微C++继承错误