RatePlayer 共有派生于类TableTennisPlayer,增加了数据成员和Rating()方法
tabtenn1.h
#pragma once
#include<string>
using std::string;
//simple base class
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; };
};
//simple derived class
class RatedPlayer :public TableTennisPlayer
{
private:
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; }
};
tabtenn1.cpp
#include "tabtenn1.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 方法
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)
{}
usett1.cpp
// usett1.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include"tabtenn1.h"
int main( void )
{
//std::cout << "Hello World!\n";
using std::cout;
using std::endl;
TableTennisPlayer player1("Tara","Boomdea",false);
RatedPlayer rplayer1(1140,"Mallory","Duck",true);
rplayer1.Name();//派生类使用了继承自基类的方法
if (rplayer1.HasTable())
cout << ":has a table.\n";
else
{
cout << ":has not a table.\n";
}
player1.Name();//基类对象使用基类的方法
if (player1.HasTable())
cout << ":has a table .\n";
else
cout << ":hasn't a table .\n";
cout << "Name: ";
rplayer1.Name();
cout << "; Rating: " << rplayer1.Rating() << endl;
//使用TableTennisPlayer 对象 初始化RatedPlayer
RatedPlayer rplayer2(1212, player1);
cout << "Name: ";
rplayer2.Name();
cout << "; Rating: " << rplayer2.Rating() << endl;
return 0;
}