#include <iostream>
using namespace std;
class A
{
public:
virtual void foo()
{
cout<<"A::foo() is called"<<endl;
}
};
class B:public A
{
public:
void foo()
{
cout<<"B::foo() is called"<<endl;
}
};
class C:public A{
void foo(){
cout << "C::foo() is calles" << endl;
}
};
int main(void)
{
A *a = new B();
a->foo(); // 在这里,a虽然是指向A的指针,但是被调用的函数(foo)却是B的!
a = new C();
a->foo();
return 0;
}
#include <iostream>
using namespace std;
class A{
private:
void show(){ cout << "private:A" << endl; }
protected:
void show2(){ cout << "protected:A" << endl; }
public:
void show3(){ cout << "public:A" << endl; }
};
class B : public A{
};
class C : protected A{
};
class D : private A{
};
int main(void){
A a;
a.show(); //fail
a.show2(); //fail
a.show3(); //ok 只有公有成员外部才可以直接调用
// //公有继承:权限属性不变
B b;
b.show(); //fail
b.show2(); //fail
b.show3(); //ok
//保护继承:公有属性转保护属性
C c;
c.show(); //fail
c.show2(); //fail
c.show3(); //fail 保护属性
//私有继承:公有属性,保护继承转私有继承
D d;
d.show(); //fail
d.show2(); //fail 私有属性
d.show3(); //fail 私有属性
return 0;
}