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

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

据了解,只有基 class 的朋友和派生 classes 可以访问基 class 的受保护成员,但在上面的示例中,我得到以下错误 "Error C2248 'base::x': cannot access protected member declared in class " 但是当我添加以下行时

friend class derived;

将其声明为朋友,我可以访问基 class 的成员,我在声明派生 class 时是否犯了一些基本错误?

派生 class 只能通过派生 class 的上下文访问基 class 的 protected 成员。换句话说,派生 class 无法通过基础 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
    }
};

你可以改变

g = &base::x;

g = &derived::x;

我的编译器实际上说我需要向 base 添加一个非默认构造函数,因为该字段未初始化。

我添加后

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

编译没有问题。