示例代码对以下两种情况进行了说明:
1. 继承时改变虚函数的权限;
2. 私有继承;
class A { public: virtual void test1() { cout << "public test1 of A" << endl; } private: virtual void test2() { cout << "private test2 of A" << endl; } protected: int p1; private: int p2; }; class B: public A { private: void test1() { cout << "privte test1 of B" << endl; } public: void test2() { cout << "public test2 of B" << endl; } }; class C: private A { public: void testProtected() { cout << p1 << endl; } }; class D: public C { public: void testProtected() { // cout << p1 << endl;//因为c私有继承A,c不能访问a的protedted成员 } }; int main() { B b; A* a = &b; a->test1();//可以访问, 权限以A为准 // a->test2();//无法访问私有成员 C c;
c.testProtected();
return 0;
}