c++中多态性 code Test


//c++中的多态主要就是利用基类指针或者引用,去指向派生类对象,调用基类虚函数时调用     //的就是派生类的数据和方法。

#include "stdafx.h"

#include

#include

#include

using namespace std;

class AAbstract

{

public:

   AAbstract(){}

   int data;

   void dis() { printf(" abstract ......data = %d \n",data); }

};

class AB_test : public AAbstract

{

public:

   AB_test():AAbstract(){}

   int bData;

   void dis() { printf(" drived ........Data = %d  bData = %d \n",data,bData); }

};

//

class bAbstract

{

public:

   bAbstract(){}

   int data;

   virtual void dis() { printf(" bbstract ......data = %d \n",data); }

};

class bB_test : public bAbstract

{

public:

   bB_test():bAbstract(){}

   int bData;

   void dis() { printf(" bdrived ........Data = %d  bData = %d \n",data,bData); }

};

int main(int argc, char* argv[])

{

   AAbstract a ;

   AB_test b;

   a.data = 1;

   a.dis();

   b.bData = 2;

   b.data = 3;

   b.dis();

 

   a = b;

   a.dis();//调用的是AAbstractfunction,只是将数据赋值给AAbstract了。

 

   AAbstract *c = new AAbstract();

   AB_test *d = new AB_test();

   d->data = 4;

   d->bData = 5;

   d->dis();

   c = d;  //the same to up state

   c->dis();

 

   AAbstract *f = new AAbstract();

   f->data = 6;

   f->dis(); //the same to up state

 

  

   bAbstract g ;

   bAbstract *p;

   bB_test h ;

   g.data = 7;

   h.bData = 8;

   h.data = 9;

   g.dis();

   h.dis();

   g = h;

   g.dis();  //虚的不起作用,必须指针

   p = &h;

   p->dis();

 

   bAbstract *j = new bAbstract();

   bB_test *k = new bB_test();

   j->data = 10;

   k->bData = 11;

   k->data = 12;

   j->dis() ;

   k->dis();

 

   j = k;

   j->dis();  //调用了虚函数 实现多台,里面data都是k的。

              //bdrived ........Data = 12  bData = 11

   bAbstract *l ;

   bB_test n;

// l->data = 13;  //第一个类没有空间,赋值是错的。

// l->dis();

   n.data = 14;

   n.bData = 15;

   n.dis();

   l  = &n;

   l->dis(); //虚函数 //和上面的是一样的

   //1.总体上,虚函数就是基类指针定义一个对象或者作为function参数 fun(aa *b)使用

   //2.基类指针指向派生的,虚function 就调用了派生类的datafunc,不用定义更多对象

   //3.基类必须是指针和引用才管用,对象型的虚不起作用。

 

  

   return 0;

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值