派生类继承了基类的公有成员和保护成员以及实现,而私有成员只能通过
基类的公有方法进行访问
派生类应该包含如下信息:
1、继承类构造函数
2、需要额外增加的成员以及实现
我们引用C++ primer plus中的例子,当然这些例子我都是手动打过一遍的
点击(此处)折叠或打开
-
#ifndef TABTEEN_H_
-
#define TABTEEN_H_
-
#include<iostream>
-
using namespace std;
-
-
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;};
-
};
-
-
class RatePlayer:public TableTennisPlayer
-
{
-
private:
-
unsigned int rating;
-
public:
-
RatePlayer(unsigned int r=0,const string & fn="none",const string& ln="none",bool ht=false);
-
RatePlayer(unsigned int r,const TableTennisPlayer& tp);
-
unsigned int Rating() const
-
{return rating;}
-
void ResetRaing(unsigned int r)
-
{rating = r;}
-
};
-
-
#endif
-
-
TableTennisPlayer::TableTennisPlayer (const string& fn,const string &ln,bool ht):firstname(fn),lastname(ln),hasTable(ht){}
-
void TableTennisPlayer::Name() const
-
{
-
std::cout<<lastname<<", "<<firstname;
-
}
-
RatePlayer::RatePlayer(unsigned int r,const string &fn,const string &ln,bool ht):TableTennisPlayer(fn,ln,ht),rating(r){}
-
//这里注意必须使用初始化列表的方式进行基类的初始化及TableTennisPlayer(fn,ln,ht)是必须的当然这里rating(r)不是必须的
-
RatePlayer::RatePlayer(unsigned int r,const TableTennisPlayer& tp):TableTennisPlayer(tp),rating(r){}
-
//这里注意TableTennisPlayer(tp)调用了默认的复制构造函数,每个类都包含一个默认的复制构造函数
-
-
主函数
-
-
#include<iostream>
-
#include "tabtenn0.h"
-
using namespace std;
-
-
int main(void)
-
{
-
TableTennisPlayer player1("Chuck","Blizzard",true);
-
TableTennisPlayer player2("Tara","Boomdea",true);
-
RatePlayer player3(1111,"gaopeng","Yjf",false);
-
player1.Name();
-
if(player1.HasTable())
-
cout<<": has a table.\n";
-
else
-
cout<<": hasn't a table.\n";
-
player2.Name();
-
if(player2.HasTable())
-
cout<<": has a table\n";
-
else
-
cout<<": hasn't a table.\n";
-
-
player3.Name();//TableTennisPlayer.Name()
-
cout<<" sorce: "<<player3.Rating();
-
if(player3.HasTable())
-
cout<<": has a table\n";
-
else
-
cout<<": hasn't a table.\n";
-
-
return 0;
- }