信管14:基类和派生类关系示例代码

来源:互联网 发布:淘宝店铺装修购买 编辑:程序博客网 时间:2024/06/01 14:37
 /*  基类和派生类关系示例,
   回答关联问题:
 面向对象有哪几个基本特征?前面几章,我们讨论了其中哪几个特征?并解释。

 掌握以下知识点:
  1.掌握什么是多态?
  2.多态分类:编译时多态和运行时多态。在C++中,二者是通过什么来实现的?
 */

/*       本例讲基类与派生类对象间兼容关系                 */

#include<iostream>  
using namespace std;

/*-------声明基类Base--------- */
class Base{                              
public:
 int i;
 Base(int x){ i=x; }                  
 void show()
  { cout<<"     Base "<<i<<endl; } 
};

/*-----声明公有派生类Derived-----*/

class Derived:public Base{  
 public:
int y;
  Derived(int x,int y1):Base(x){y=y1; }
void show()
  { cout<<"     Base, i="<<i<<"  derive, y="<<y<<endl; } 
}; 

/*----普通函数,形参为基类对象的引用---*/

void fun(Base &bb)    
{ cout<<"      i= "<<bb.i<<endl; }

/*-----主函数----*/
int main()
{ Base b1(100);
  Derived d1(11,1),d2(22,2),d3(33,3),d4(44,4); 
  
  cout<<"   1:********************"<<endl;
  b1.show(); 
 
  cout<<"   2:********************"<<endl;
  d1.show();
  d1.Derived::show();
  d1.Base::show();

  cout<<"   3:********************"<<endl; 
  b1=d1; 
  b1.show();  
  
  Base &b2=d2;         
  b2.show();

  cout<<"   4:********************"<<endl; 
  Base *bp=&b1;   
  bp->show();
  bp=&d1;                           //基类指针可以指向公有派生类对象  
  bp->show();
  d1.show();
  //  bp->Derived::show();         //错误,基类指针可以指向公有派生类对象,但能能访问从基类来的成员成员

  cout<<"   5:********************"<<endl;
  fun(d4); 

// Derived *p2=&b1;                //错误,派生类指针不能指向基类对象

  system("pause");
  return 0; 
}
0 0