码迷,mamicode.com
首页 > 编程语言 > 详细

C++类的继承实例

时间:2014-07-16 18:03:10      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   使用   os   2014   

首先由三个类分别为DateType(日期类)、TimeType(时间类)、DateTimeType(日期时间内)。详细代码例如以下:

#include <iostream>
using namespace std;

class DateType
{
	int year,month,day;
public:
	DateType(int year = 2000,int month = 12,int day = 1)
	{
		this->year = year;
		this->month = month;
		this->day = day;
		cout<<"DateType的构造函数"<<endl;
	}

	void display()
	{
		cout<<year<<"年"<<month<<"月"<<day<<"日"<<endl;
	}

	~DateType()
	{
		cout<<"DateType的析构函数"<<endl;
	}
	
};

class TimeType
{
	int h,m,s;
public:
	TimeType(int h = 12,int m = 30,int s = 30)
	{
		this->h = h;
		this->m = m;
		this->s = s;
		cout<<"TimeType的构造函数"<<endl;
	}
	
	void display()
	{
		cout<<h<<"时"<<m<<"分"<<s<<"秒"<<endl;
	}
	
	~TimeType()
	{
		cout<<"TimeType的析构函数"<<endl;
	}
};


class DateTimeType:public DateType,public TimeType
{
public:
	DateTimeType(int y=2014,int month=5,int d=12,int h=17,int m=2,int s=10):TimeType(h,m,s),DateType(y,month,d){}
	void display()
	{
		DateType::display();
		TimeType::display();
	}
};

int main()
{
	DateTimeType dt;
	dt.display();
	return 0;
}

最后的结果例如以下:

bubuko.com,布布扣

最后分析一下我在这个实验中学到了什么:

1.派生类运行例如以下:

   a.调用基类的构造函数,调用顺序是它们被继承时声明的基类的顺序。。

   b.调用派生类的构造函数

   c.运行派生类的析构函数

   d.运行基类的析构函数(顺序相反)

2.假设一个类中的构造函数如DateType(int year = 2000,int month = 12,int day = 1),声明对象时能够使用DateType d来声明,尽管并没有无參的构造函数。而假设加入?了无參的构造函数,则会编译错误。

3.一个类继承多个类时,构造函数调用的顺序跟声明时(比如class DateTimeType:public DateType,public TimeType)一致,而不是看(DateTimeType(int y=2014,int month=5,int d=12,int h=17,int m=2,int s=10):TimeType(h,m,s),DateType(y,month,d){},这里的顺序没有影响)。

4.假设继承构造时写成这样:

	DateTimeType(int y=2014,int month=5,int d=12,int h=17,int m=2,int s=10):TimeType(h,m,s)
	{
		DateType::DateType(y,month,d);
	}

结果中日期为2000年12月10日,说明必须使用參数列表。这里实际上调用的是DateType的默认无參构造函数,不信能够将函数写成这样

	DateType(int year,int month,int day)
	{
		this->year = year;
		this->month = month;
		this->day = day;
		cout<<"DateType的构造函数"<<endl;
	}

	DateType()
	{
		cout<<"DateType的无參构造函数"<<endl;
	}

然后结果就成下图这样了,这充分说明了:“要是使用基类的带參数的构造函数,必须使用參数列表,否则仅仅能调用基类的无參构造函数”。


bubuko.com,布布扣




C++类的继承实例,布布扣,bubuko.com

C++类的继承实例

标签:style   blog   http   使用   os   2014   

原文地址:http://www.cnblogs.com/hrhguanli/p/3847412.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!