C++公有继承
C++提供了比修改代码更好的方法来扩展和修改类,这种方法就叫类继承,他能够从已有的类派生出新的类,而派生类继承了原有类(基类)的特征,包括方法。从一个类派生出另一个类时,原始类叫基类,继承类叫派生类。
示例TableTennisPlayer派生出RatedPlayer
TableTennisPlayer类
#ifndef INHERITATE_TABTENN0_H
#define INHERITATE_TABTENN0_H
#include <string>
using std::string;
class TableTennisPlayer {
private:
string firstname;
string lastname;
bool hasTable;
public:
TableTennisPlayer(const string &fn="none", const string &ln="none", bool ht= false);
void Name()const ;
bool HasTable()const {return hasTable;};
void ResetTable(bool v){hasTable=v;};
};
#endif //INHERITATE_TABTENN0_H
#include "tabtenn0.h"
#include <iostream>
TableTennisPlayer::TableTennisPlayer(const string &fn,
const string & ln, bool ht):firstname(fn),
lastname(ln),hasTable(ht){}
void TableTennisPlayer::Name() const {
std::cout<<lastname<<", "<<firstname;
}
RatedPlayer类
#ifndef INHERITATE_RATEDPLAYER_H
#define INHERITATE_RATEDPLAYER_H
#include "tabtenn0.h"
class RatedPlayer : public TableTennisPlayer{//继承
private:
unsigned int rating;
public:
RatedPlayer(unsigned int r=0, const string &fn="none", const string &ln="none", bool ht = false);
RatedPlayer(unsigned int r, const TableTennisPlayer &tp);
unsigned int Rating()const { return rating;}
void ResetRating(unsigned int r ){rating=r;}
};
#endif //INHERITATE_RATEDPLAYER_H
#include "RatedPlayer.h"
RatedPlayer::RatedPlayer(unsigned int r, const string &fn, const string &ln, bool ht):TableTennisPlayer(fn,ln,ht){
rating=r;
}
RatedPlayer::RatedPlayer(unsigned int r, const TableTennisPlayer &tp):TableTennisPlayer(tp){
rating=r;
}
测试代码
#include <iostream>
#include "tabtenn0.h"
#include "RatedPlayer.h"
int main() {
using std::cout;
using std::endl;
TableTennisPlayer player1("Tara","Boomda", false);
RatedPlayer rplayer1(1600,"Mallory","Duck", true);
rplayer1.Name();
cout<<rplayer1.HasTable()<<endl;
cout<<rplayer1.Rating()<<endl;
rplayer1.ResetRating(555);
cout<<rplayer1.Rating()<<endl;
return 0;
}
派生类和基类之间的特殊关系
1.派生类可以使用基类的公有方法,派生类继承了基类的方法所以这样做没有问题
2.派生类对象可以赋给基类指针,派生类对象的引用也可以赋给基类引用,反过来却不行
3.一个函数的参数为基类引用时,我们可以赋予派生类对象的引用,这样这个函数也可以为派生类服务