访问控制和静态成员

当指定基类用作 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。 指针是隐式类型 Derived2 *。 若要选择 CountOf 功能,必须将 键入 Base *。 ,因为 Base 是私有间接基类为 Derived2,此类转换是不允许的。 对一个私有基类类型的转换为指针只接受对立即派生类。 因此,可以将类型 Derived1 * 指针类型 Base *。

请注意显式调用 CountOf 功能,则为;,而不使用指针,引用,或选择它的对象,并不表示转换。 因此,调用允许的。

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

请参见

参考

基类的访问说明符