基类或派生类相互指向或引用

先写一个基类Base 再写一个派生类derive简单实现它们的构造虚构函数

class Base
{
public:
 Base(int  data = 0) :ma(data)
 {
  cout << "Base()" << endl;
 }
 void Show()
 {
  cout << "Base::Show()" << endl;
 }
 void Show(int data)
 {
  cout << "Base::Show(int)" << endl;
 }
 void* operator new(size_t size)
 {
  int *p = (int*)malloc(size);
  cout <<"new::"<< p << endl;
  if (p == NULL)
  {
   throw bad_alloc();
  }
  return p;
 }
 void operator delete(void* ptr)
 {
  cout << "delete::"<<ptr << endl;
  free(ptr);
 }
 ~Base()
 {
  cout << "~Base()" << endl;
 }
protected:
 int ma;
};


class Derive : public Base
{
public:
 Derive(int  data) :mb(data), Base(data)
 {
  cout << "Derive()" << endl;
 }
 virtual void Show()//编译器认为这个函数也是虚函数
 {
  cout << "Derive::Show()" << endl;
 }
 ~Derive()

 {
  cout << "~Derive()" << endl;
 }
private:
 int mb;
};

int main()
{
 Base b(10);
 Derive d(10);
 //Derive* p1 = &b; //??  派生类的指针  没办法指向基类的对象
 //Base* p2 = &d;//基类的指针  指向派生类的对象 
 //Derive &b1 = b;//派生类的引用  没办法引用基类对象
 Base &d1 = d;//基类的引用可以引用派生类的对象
 return 0;
}



int main()
{
 Derive d(10);
 Base* p = &d;
 p->Show();
 /*
 Base  编译阶段  静态的绑定 早绑定 静态的多态 call  Base::Show
  函数重载  模板 
 */
 /*
  运行时==>动态的绑定  晚绑定     运行时的多态
  call  eax
  继承:虚函数
 */
 cout << sizeof(Base) << endl;
 cout << sizeof(Derive) << endl;
 cout << typeid(p).name() << endl;//class Base*
 cout << typeid(*p).name() << endl;//class Base
 return 0;
}
int main()
{
 Base b(10);
 Derive d(20);
 
 b.Show();//静态的多态
 d.Show(); //静态的多态
 Base *p1 = &b;//base
 p1->Show();动态的
 Base *p2 = &d;
 p2->Show();//动态的多态base
 Derive *p3 = &d;
动态的多态
 p3->Show();//derive
 return 0;
}

/*
虚函数
1.能取地址
2.对象
构造函数 不能
析构函数 可以
inline函数 不能
static函数 不能
*/
/*
 1.什么时候会产生运行时多态的编译或者调用
  指针指向或者引用时,调用虚函数
*/
int main()
{
 Base *p = new Derive(10);
 /*
  vfptr
  Base::
    ma
  mb
 */
 p->Show();
 //p = (Base*)((int)p - 4);
 delete p;
 //(*p).~Base();
 /*
  void free(void *ptr);
 */
 return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值