简体   繁体   English

派生类无法访问基类的受保护成员

[英]Derived class cannot access the protected member of the base class

Consider the following example 请考虑以下示例

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

As per knowledge only friends and derived classes of the base class can access the protected members of the base class but in the above example I get the following error "Error C2248 'base::x': cannot access protected member declared in class " but when I add the following line 根据知识,只有基类的朋友和派生类可以访问基类的受保护成员,但在上面的示例中我得到以下错误"Error C2248 'base::x': cannot access protected member declared in class "但是当我添加以下行

friend class derived;

declaring it as friend , I can access the members of the base class , did I do some basic mistake in the declaring the derived class ? 声明它是朋友,我可以访问基类的成员,我在声明派生类时做了一些基本错误吗?

The derived class could access the protected members of base class only through the context of the derived class. 派生类只能通过派生类的上下文访问基类的protected成员。 On the other word, the derived class can't access protected members through the base class. 换句话说,派生类无法通过基类访问protected成员。

When a pointer to a protected member is formed, it must use a derived class in its declaration: 当形成指向受保护成员的指针时,它必须在其声明中使用派生类:

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

You can change 你可以改变

g = &base::x;

to

g = &derived::x;

My compiler actually said I needed to add a non-default constructor to base because the field is not initialized. 我的编译器实际上说我需要一个非默认构造函数添加到base ,因为现场未初始化。

After I added 我加了之后

base() : g(&base::x) {}

it did compile without problems. 它确实编译没有问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM