继承与派生类 学习笔记2

派生类的构造函数与析构函数

注意:派生类是不能继承基类的构造函数和析构函数的。对于派生类的构造函数,由于派生类不能直接访问基类的私有成员,只能通过基类的方法进行访问,所以派生类构造函数必须使用基类的构造函数。
派生类需要析构函数完成一些必要的清理工作,必须定义自己的的析构函数。

头函数:

#ifndef INHERIT_H_
#define INHERIT_H_

const int READY=0;
const int RUNNING=1;

class Car
{
private:
	int status;
public:
	Car(int s=READY);
	void StartCar();
	void StopCar();
	int GetStatus();
};

class FireCar:public Car
{
private:
	char way[10];
public:
	FireCar(char* c="water",int s=READY);
	void PutFire(); //增加的方法
};
#endif



方法:
#include<iostream>
#include<cstring>
#include"Inherit.h"
using namespace std;

Car::Car(int s)
{
	status=s;
}

void Car::StartCar()
{
	status=RUNNING;
	cout << "the car is running." << endl;
}

void Car::StopCar()
{
	status=READY;
	cout << "the car is stopped." << endl;
}

int Car::GetStatus()
{
	return status;
}

FireCar::FireCar(char* c,int s):Car(s)
{
	strcpy(way,c);
}

void FireCar::PutFire()
{
	if(GetStatus()==RUNNING)
		cout << "this FireCar uses" << way
		<< "to put out the fire." << endl;
	else
		cout << "Can't use a unusing FireCar to put out a fire." << endl;
		
}


主函数:
#include<iostream>
#include"Inherit.h"
using namespace std;

int main()
{
	FireCar fc1;
	FireCar fc2("DryIce",RUNNING);

	cout << "For FireCar1:" << endl;
	fc1.PutFire();
	fc1.StartCar();
	fc1.PutFire();

	cout << endl;
	cout << "For FireCar2:" <<endl;
	fc2.PutFire();

	return 0;
}

运行结果:



 

多重继承
代码:
//Multiin.h
#ifndef MULTIIN_H_
#define MULTIIN_H_
class Student
{
private:
	int Number;
	char academy[20];
public:
	Student(int n=1,char* aca="Sichuang University");
	int GetNumber() const
	{
		return Number;
	}
	char* GetAcad()
	{
		return academy;
	}
};

class Player
{
private:
	char event[20];
public:
	Player(char* ev="football");
	char * GetEvent()
	{
		return event;
	}
};

class StuPlayer:public Student,public Player
{
private:
	char Name[10];
public:
	StuPlayer(char* n="John",char* a="Sichuan University",int i=1,char* e="football");
	void ShowMe();
};
#endif

//Mltiin.cpp

#include<iostream>
#include<cstring>
#include"Multiin.h"
using namespace std;
Student::Student(int n,char* aca)
{
	Number=n;
	strcpy(academy,aca);
}

Player::Player(char* ev)
{
	strcpy(event,ev);
}

StuPlayer::StuPlayer(char* n,char* a,int i,char* e)
:Student(i,a),Player(e)
{
	strcpy(Name,n);
}

void StuPlayer::ShowMe()
{
	cout << "My name is" << Name << endl;
	cout << "I am a student in" << GetAcad() << endl;
	cout << "I am also a player. I play" << GetEvent() << endl;
}

//usemult.cpp
#include<iostream>
#include"Multiin.h"
using namespace std;

int main()
{
	StuPlayer st1;
	StuPlayer st2("Emily","Wuhan University",8,"basketball");
	cout << "For student player 1:" << endl;
	st1.ShowMe();
	cout << endl;
	
	cout << "For student player 2:" << endl;
	st2.ShowMe();

	return 0;
}

结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值