继承
- 可在已有类的基础上添加功能
- 可给类添加数据
- 可修改类方法的行为
从一个类派生出另一个类时,原始类称为基类,继承类成为派生类
Webtown俱乐部决定跟踪乒乓球会员,设计一个简单的TableTennisPlayer类
tabtenn0.h
#ifndef TABTENN0_H_
#define TABTENN0_H_
#include <string>
using std::string;
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 };
};
#endif
tabtenn0.cpp
#include "tabtenn0.h"
#include <iostream>
// 将string作为参数时,将调用接受const string&作为参数的string构造函数
TableTennisPlayer::TableTennisPlayer (const string & fn,
const string & ln, bool ht) : firstname(fn),
lastname(ln), hasTable(ht) {}
//构造函数成员初始化另外一种形式
/*
TableTennisPlayer::TableTennisPlayer (const string & fn,
const string & ln, bool ht)
{
firstname = fn;
lastname = ln;
hasTable = ht;
}
*/
void TableTennisPlayer::Name() const
{
std::cout << lastname << "," << firstname;
}
usett0.cpp
#include <iostream>
#include "tabtenn0.h"
int main (void)
{
using std::cout;
// C-风格字符串作为参数,初始化string对象时,将自动调用构造函数
TableTennisPlayer player1("Chuck", "Blizzard", true); // 将调用接受const char* 作为参数的string构造函数
TableTennisPlayer player2("Tara", "Boomdea", false); // string类有一个将const char*作为参数的构造函数
player1,Name();
if (player1,HasTable())
cout << ": has a table.\n";
else
cout << ": hasn't a table.\n";
player2.Name();
if (player2.HasTable())
cout << ": has a table";
else
cout << ": hasn't a table.\n";
return 0;
}
输出
Blizzard, Chuck: has a table.
Boomdea, Tara: hasn’t a table.