派生类无法访问基类的受保护成员
Derived class cannot access the protected member of the base class
考虑以下示例
class base
{
protected :
int x = 5;
int(base::*g);
};
class derived :public base
{
void declare_value();
derived();
};
void derived:: declare_value()
{
g = &base::x;
}
derived::derived()
:base()
{}
根据知识,只有基类的友元和派生类可以访问基类的受保护成员,但在上面的示例中,我收到以下错误"Error C2248 'base::x': cannot access protected member declared in class "
但是当我添加以下行时
friend class derived;
将其声明为朋友,我可以访问基类的成员,我在声明派生类时是否犯了一些基本错误?
派生类只能通过派生类的上下文访问基类的protected
成员。换句话说,派生类无法通过基类访问protected
成员。
形成指向受保护成员的指针时,它必须使用派生的 类在其声明中:
struct Base { protected: int i; }; struct Derived : Base { void f() { // int Base::* ptr = &Base::i; // error: must name using Derived int Base::* ptr = &Derived::i; // okay } };
您可以更改
g = &base::x;
自
g = &derived::x;
我的编译器实际上说我需要向base
添加一个非默认构造函数,因为该字段未初始化。
在我添加之后
base() : g(&base::x) {}
它确实编译没有问题。
相关文章:
- C++:无法访问声明的受保护成员
- 相同的层次结构,访问基类的受保护成员时的行为不同
- 同一模板类但模板类型的受保护成员
- 派生类无法访问基类的受保护成员
- 继承期间受保护成员的皮条
- 如何将超类的受保护成员访问到其派生类. 如果已在派生类中声明了具有相同名称的函数?
- 是否可以基于私有/受保护成员分配类枚举?
- 依赖模板基础的受保护成员
- 无法从派生类型的作用域访问另一个实例的受保护成员
- 为什么我无法使用受保护/私有继承访问派生实例中基类的受保护成员?
- 将对象强制转换为派生类以访问父类的受保护成员
- 使从一个基类派生的类能够使用继承的受保护成员
- 派生类如何使用基类的受保护成员
- 访问派生类C++中的受保护成员
- 访问基类的受保护成员
- 如何访问多个继承类中的受保护成员
- 如何从另一个类的基类访问派生类中的受保护成员
- 无法访问派生类中的基本受保护成员!(在虚函数中)
- 如何通过派生类访问基类的受保护成员?
- 如果孩子不需要父母班级的所有受保护成员,这是不好的班级设计吗?