C++派生类与构造函数示例代码

#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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值