派生类的构造函数与析构函数
注意:派生类是不能继承基类的构造函数和析构函数的。对于派生类的构造函数,由于派生类不能直接访问基类的私有成员,只能通过基类的方法进行访问,所以派生类构造函数必须使用基类的构造函数。
派生类需要析构函数完成一些必要的清理工作,必须定义自己的的析构函数。
头函数:
#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;
}
结果: