P481tabtenn0

编程环境为Qt Creator 4.0.3 (Community)
tabtenn0.h

#ifndef TABTENN0_H
#define TABTENN0_H

#include <string>
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 ResetTabel(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 ResetRating(unsigned int r){rating=r;}
};
#endif // TABTENN0_H

main.cpp

#include <iostream>
#include "tabtenn0.h"

using namespace std;

void Show(const TableTennisPlayer &rt);

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;
}
RatePlayer::RatePlayer(unsigned int r,
                       const TableTennisPlayer &tp):TableTennisPlayer(tp),rating(r)
{

}
int main(int argc, char *argv[])
{

    cout << "Hello World!" << endl;
    TableTennisPlayer player1("Tara","Boomdea",false);
    RatePlayer rplayer1(1140,"Mallory","Duck",true);
    rplayer1.Name();  //继承的类使用基类的方法
    if(rplayer1.HasTable())
    {
        cout<<":has a table\n"<<endl;
    }
    else
    {
        cout<<":hasn't a table"<<endl;
    }
    player1.Name();  //基类使用基类的方法
    if(player1.HasTable())
    {
        cout<<":has a table"<<endl;
    }
    else
    {
        cout<<"hasn't a table"<<endl;
    }
    //使用基类的对象初始化继承类
    RatePlayer rplayer2(1212,player1);
    cout<<"Name:";
    rplayer2.Name();
    cout<<": Rating:"<<rplayer2.Rating()<<endl;
    Show(player1);
    Show(rplayer1);
    //将基类对象初始化为派生类对象
    RatePlayer olaf1(1840,"Olaf","Loaf",true);  //派生类对象
    TableTennisPlayer olaf2(olaf1);  //基类对象
    olaf2.Name();

    return 0;
}
void Show(const TableTennisPlayer &rt)
{
    using std::cout;
    cout<<"Name:";
    rt.Name();
    cout<<"\nTable:";
    if(rt.HasTable())
    {
        cout<<"yes"<<endl;
    }
    else
    {
        cout<<"no"<<endl;
    }
}

运行结果如下

猜你喜欢

转载自www.cnblogs.com/Manual-Linux/p/9623351.html