#pragma once
//基类.h
class TabletennisPlayer
{
public:
TabletennisPlayer(const char * fn = "none",
const char *ln = "none", bool ht = false);
void Name() const;
bool isHasTable()const
{
return hasTable;
}
void resTable(bool v)
{
hasTable = v;
}
virtual ~TabletennisPlayer();
private:
enum {LIM=20};
char firstName[LIM];
char lastName[LIM];
bool hasTable;
};
//基类.c文件
#include "TabletennisPlayer.h"
#include "string.h"
#include <iostream>
TabletennisPlayer::TabletennisPlayer(const char *fn, const char *ln, bool ht)
{
strncpy_s(firstName, fn, LIM - 1);
firstName[LIM - 1] = '\0';
strncpy_s(lastName, ln, LIM - 1);
lastName[LIM - 1] = '\0';
hasTable = ht;
}
void TabletennisPlayer::Name()const
{
std::cout << lastName << "," << firstName;
}
TabletennisPlayer::~TabletennisPlayer()
{
}
派生类代码
#pragma once
#include "TabletennisPlayer.h"
//派生类.h
class RatePlayer :public TabletennisPlayer//派生类的使用方法:
{
public:
//派生类需要自己的构造函数和析构函数
~RatePlayer();
RatePlayer(unsigned int r = 0, const char *fn = "none",
const char *ln = "none", bool ht = false);
RatePlayer(unsigned int r, const TabletennisPlayer & tp);
unsigned int Rating(void)
{
return rate;
}
void resetRating(unsigned int r)
{
rate = r;
}
private:
unsigned int rate;
};
// 派生类.c程序
#include "RatePlayer.h"
#include "TabletennisPlayer.h"
/*派生类构造函数的使用方法*/
/*
派生类不能直接访问基类的私有成员,必须通过基类的公有方法访问,
派生类的构造函数必须使用基类的构造函数.
不要给构造函数赋默认参数。
*/
RatePlayer::RatePlayer(unsigned int r, const char *fn, const char*ln , bool ht):TabletennisPlayer(fn, ln, ht)
{
r = rate;
}
RatePlayer::RatePlayer(unsigned int r, const TabletennisPlayer &tp) : TabletennisPlayer(tp), rate(r)
{
}
/*
派生类的析构函数
*/
RatePlayer::~RatePlayer()
{
}
main()函数代码
#include <iostream>
#include "TabletennisPlayer.h"
#include "RatePlayer.h"
using namespace std;
int main(void)
{
TabletennisPlayer player1("Tom", "cat", true);// 必须先创建基类对象
//TabletennisPlayer player2("hom", "cat", false);
RatePlayer rateplayer(120, "thr", "rong", true);//创建派生类对象
rateplayer.Name();
if (rateplayer.isHasTable())
{
cout << "has table" << endl;
};
#if 0
player1.Name();
if (player1.isHasTable())
{
cout<<"has table" << endl;
}
else
{
cout <<" do not has table" << endl;
};
player2.Name();
if (player2.isHasTable())
{
cout << "has table" << endl;
}
else
{
cout <<" do not has table" << endl;
};
#endif
return 0;
}