- //菱形继承
- class Person
- {
- public:
- A()
- :_a(1)
- {}
- protected:
- int _a;
- };
- class Student :virtual public Person
- {
- public:
- B()
- :_b(2)
- {}
- protected:
- int _b;
- };
- class Teacher :virtual public Person
- {
- public:
- C()
- :_c(3)
- {}
- protected:
- int _c;
- };
- class Assistant :public Teacher, public Student
- {
- public:
- D()
- :_d(4)
- {}
- protected:
- int _d;
- };
- int main()
- {
- Assistant d;
- cout << sizeof(d) << endl;
- system("pause");
- return 0;
- }
-
- //多态的原理
- class Person
{
public:
virtual void BuyTickets()
{
cout << "买票" << endl;
}
};
class Student:public Person
{
public:
virtual void BuyTickets()
{
cout << "买半价票" << endl;
}
};
void fun(Person&p)
{
p.BuyTickets();
}
int main()
{
Person p;
Student s;
fun(p);
fun(s);
}
- 多态的实现原理自我感觉是靠虚函数的__vfptr来指向是调用基类还是派生类的...
菱形继承与探索多态的原理
最新推荐文章于 2022-07-23 09:43:37 发布