首页 > 学院 > 开发设计 > 正文

菱形继承与探索多态的原理

2019-11-08 19:45:05
字体:
来源:转载
供稿:网友
//菱形继承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来指向是调用基类还是派生类的...
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表