c++多重继承、多态

一、c++多重继承

派生类构造函数的执行顺序为:

1、调用基类构造函数,调用顺序按照它们被继承时声明的基类名顺序执行。

2、调用内嵌对象构造函数,调用顺序按各个对象在派生类内声明的顺序执行。

3、执行派生类构造函数体重的内容。

派生类析构函数执行顺序为:

1、执行派生类析构函数。

2、执行内嵌对象的析构函数。

3、执行基类析构函数。

#include <iostream>
using namespace std;
class CTimeType
{
public:
 CTimeType(int h = 12,int m = 0,int s = 0)
 {
  hour = h;
  minute = m;
  second = s;
 }
 void display()
 {
  cout<<hour<<" : "<<minute<<" : "<<second<<endl;
 }
 void SetTime(int h,int m,int s)
 {
  hour = h;
  minute = m;
  second = s;
 }
private:
 int hour;
 int minute;
 int second;
};
class CDataType
{
public:
 CDataType(int mon = 1,int d = 1,int y = 2008)
 {
  month = mon;
  day = d;
  year = y;
 }
 void display()
 {
  cout<<month<<" / "<<day<<" / "<<year<<endl;
 }
 void SetData(int mon,int d,int y)
 {
  month = mon;
  day = d;
  year = y;
 }
private:
 int month;
 int day;
 int year;
};
class CDataTimeType:public CDataType,public CTimeType
{
public:
 CDataTimeType(int mon = 1,int d = 1,int y = 2000,int h = 0,int m = 0,
  int s = 0):CDataType(mon,d,y),CTimeType(h,m,s){}
 void display()
 {
  CTimeType::display();
  CDataType::display();
 }
protected:
private:
};
int main()
{
 cout<<"类的多重继承演示"<<endl;
 CDataTimeType dt(1,2,2011,6,7,30);
 cout<<"调用CDataTimeType类构造函数设定的初始日期、时间为: "<<endl;
 dt.display();
 dt.SetData(5,8,2014);
 dt.SetTime(16,29,35);
 cout<<"调用基类成员函数修改后的日期、时间为: "<<endl;
 dt.display();
 return 0;
}

 

二、多态性(编译时的多态性和运行时的多态性)

1、编译时的多态性主要是通过函数的重载和运算符的重载来实现。

2、运行时多态则是通过虚函数来实现。(运行时多态性是指在程序执行前,无法根据函数名和参数来确定该调用哪一个函数,必须在程序执行过程中,根据执行的具体情况来动态地确定)

注意:将类中具有共性的成员函数声明为虚函数,派生来定义虚函数的时候,必须保证函数返回值的类型和参数与基类中的声明完全一致。

 

#include <iostream>
using namespace std;
class CFigure
{
public:
 void SetDim(double i,double j=0.0)
 {//设置图像参数
  x = i;
  y = j;
 }
 virtual void GetShowArea()
 {
  cout<<"无法计算面积\n";
 }
protected:
 double x,y;
private:
};
class CTriangle:public CFigure
{
public:
 void GetShowArea()
 {
  cout<<"三角形:底边长:"<<x<<" 高:"<<y<<" 面积:"<<x*y*0.5<<endl;
 }
protected:
private:
};
class CRect:public CFigure
{
public:
 void GetShowArea()
 {
  cout<<"矩形:长:"<<x<<" 宽:"<<y<<" 面积:"<<x*y<<endl;
 }
protected:
private:
};
class CCricle:public CFigure
{
public:
 void GetShowArea()
 {
  cout<<"圆形:半径:"<<x<<" 面积:"<<3.14159*x*x<<endl;
 }
protected:
private:
};
int main()
{
 cout<<"使用虚函数实现运行时多态";
 CFigure *figure;
 CTriangle triangle;
 CRect rect;
 CCricle circle;
 figure = &triangle;
 figure->SetDim(8.0,5.0);//设置三角形的参数
 figure->GetShowArea();//calculator and show area

 figure = &rect;
 figure->SetDim(10.0,5.0);
 figure->GetShowArea();
 
 figure = &circle;
 figure->SetDim(10.0);
 figure->GetShowArea();
 return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值