访问控制和静态成员

在将基类指定为 private 时,它只影响非静态成员。 在派生类中,公共静态成员仍是可访问的。 但是,使用指针、引用或对象访问基类的成员需要转换,此时将再次应用访问控制。 请看下面的示例:

// access_control.cpp
class Base
{
public:
    int Print();             // Nonstatic member.
    static int CountOf();    // Static member.
};

// Derived1 declares Base as a private base class.
class Derived1 : private Base
{
};
// Derived2 declares Derived1 as a public base class.
class Derived2 : public Derived1
{
    int ShowCount();    // Nonstatic member.
};
// Define ShowCount function for Derived2.
int Derived2::ShowCount()
{
   // Call static member function CountOf explicitly.
    int cCount = Base::CountOf();     // OK.

   // Call static member function CountOf using pointer.
    cCount = this->CountOf();  // C2247. Conversion of
                               //  Derived2 * to Base * not
                               //  permitted.
    return cCount;
}

在前面的代码中,访问控制禁止从指向 Derived2 的指针转换为指向 Base 的指针。 this 指针是 Derived2 * 类型的隐式表示形式。 若要选择 CountOf 函数,则必须将 this 转换为 Base * 类型。 不允许执行此类转换,因为 Base 是 Derived2 的私有间接基类。 到私有基类类型的转换仅对于指向立即派生类的指针是可接受的。 因此,可以将 Derived1 * 类型的指针转换为 Base * 类型。

请注意,显式调用 CountOf 函数而不使用指针、引用或对象来选择它,则表示没有转换。 因此,允许该调用。

派生类 T 的成员和朋友可以将指向 T 的指针转换为指向 T 的私有直接基类的指针。

请参见

参考

基类的访问说明符