且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我可以从派生类中的静态函数访问基类受保护的成员吗?

更新时间:2023-02-15 15:07:20

一般来说(无论函数是否是静态的),一个
成员函数的派生类只能访问其类型的对象的受保护的基本
类成员。如果静态类型不是派生类
(或从其派生的类)的静态类型,则它不能访问受保护的
基本成员。所以:

In general (regardless of whether the function is static or not), a member function of the derived class can only access protected base class members of objects of its type. It cannot access protected members of the base if the static type is not that of the derived class (or a class derived from it). So:

class Base {
protected:
    int var;
 } ;

class Derived : public Base {
    static void f1( Derived* pDerived )
    {
        pDerived->var = 2; // legal, access through Derived...
    }
    static bool Process( Base *pBase )
    {
        pBase->var = 2 ;  // illegal, access not through Derived...
    }
} ;