C++ 派生类
定义派生类的基类
#ifndef PRO1_TABTENN_H
#define PRO1_TABTENN_H
class TableTennisPlayer {
private:
enum {LIM = 20};
char firstname[LIM];
char lastname[LIM];
bool hasTable;
public:
TableTennisPlayer(const char* fn = "none", const char* ln = "none", bool ht = false);
void Name()const ;
bool HasTable()const { return hasTable;};
void ResetTable(bool v){hasTable = v;};
};
#endif //PRO1_TABTENN_H
#include "tabtenn.h"
#include <iostream>
#include <cstring>
using namespace std;
TableTennisPlayer::TableTennisPlayer(const char *fn, const char *ln, bool ht) {
strncpy(firstname, fn, LIM - 1);
firstname[LIM - 1] = '\0';
strncpy(lastname, ln, LIM -1);
lastname[LIM - 1] = '\0';
hasTable = ht;
}
void TableTennisPlayer::Name() const {
cout << lastname << " , " << firstname;
}
#include <iostream>
#include "module6_extends/tabtenn.h"
using namespace std;
void usett(){
TableTennisPlayer player1("Chuck", "Blizzard", true);
TableTennisPlayer player2("Tara", "Boomdea", false);
player1.Name();
if (player1.HasTable()) {
cout << ":has a table.\n";
} else{
cout << ":has't a table.\n";
}
player2.Name();
if (player2.HasTable()) {
cout << ":has a table.\n";
} else{
cout << ":has't a table.\n";
}
}
int main() {
usett();
return 0;
}
使用派生类
class RatedPlayer:public TableTennisPlayer{
private:
unsigned int rating;
public:
RatedPlayer(unsigned int r = 0, const char* fn = "none", const char* ln = "none", bool ht = false);
RatedPlayer(unsigned int r, const TableTennisPlayer & tp);
unsigned int Rating(){ return rating; }
void ResetRating(unsigned int r){rating = r;}
};
RatedPlayer::RatedPlayer(unsigned int r, const char *fn, const char *ln, bool ht):TableTennisPlayer(fn, ln, ht){
rating = r;
}
RatedPlayer::RatedPlayer(unsigned int r, const TableTennisPlayer &tp):TableTennisPlayer(tp), rating(r) {}
#include <iostream>
#include "module6_extends/tabtenn.h"
using namespace std;
void usett(){
TableTennisPlayer player1("Chuck", "Blizzard", true);
TableTennisPlayer player2("Tara", "Boomdea", false);
RatedPlayer ratedPlayer(1140, "Mallory", "Duck", true);
ratedPlayer.Name();
if (ratedPlayer.HasTable()) {
cout << ":has a table.\n";
}else{
cout << ":has't a table.\n";
}
player1.Name();
if (player1.HasTable()) {
cout << ":has a table.\n";
} else{
cout << ":has't a table.\n";
}
player2.Name();
if (player2.HasTable()) {
cout << ":has a table.\n";
} else{
cout << ":has't a table.\n";
}
cout << "Name: ";
ratedPlayer.Name();
cout << ":Rating: " << ratedPlayer.Rating() << endl;
RatedPlayer ratedPlayer1(1221, player1);
cout << "Name: ";
ratedPlayer1.Name();
cout << ":Rating :" << ratedPlayer1.Rating() << endl;
}
int main() {
usett();
return 0;
}