当前位置:嗨网首页>书籍在线阅读

02-一个简单的基类

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

13.1 一个简单的基类

从一个类派生出另一个类时,原始类称为基类,继承类称为派生类。为说明继承,首先需要一个基类。Webtown俱乐部决定跟踪乒乓球会会员。作为俱乐部的首席程序员,需要设计一个简单的TableTennisPlayer类,如程序清单13.1和程序清单13.2所示。

程序清单13.1 tabtenn0.h

// tabtenn0.h -- a table-tennis base class
#ifndef TABTENN0_H_
#define TABTENN0_H_
#include <string>
using std::string;
// simple base class
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

程序清单13.2 tabtenn0.cpp

//tabtenn0.cpp -- simple base-class methods
#include “tabtenn0.h"
#include <iostream>
TableTennisPlayer::TableTennisPlayer (const string & fn,
    const string & ln, bool ht) : firstname(fn),
           lastname(ln), hasTable(ht) {}
void TableTennisPlayer::Name() const
{
    std::cout << lastname << “, “ << firstname;
}

TableTennisPlayer类只是记录会员的姓名以及是否有球桌。有两点需要说明。首先,这个类使用标准string类来存储姓名,相比于使用字符数组,这更方便、更灵活、更安全,而与第12章的String类相比,这更专业。其次,构造函数使用了第12章介绍的成员初始化列表语法,但也可以像下面这样做:

TableTennisPlayer::TableTennisPlayer (const string & fn,
                   const string & ln, bool ht)
{
    firstname = fn;
    lastname = ln;
    hasTable = ht;
}

这将首先为firstname调用string的默认构造函数,再调用string的赋值运算符将firstname设置为fn,但初始化列表语法可减少一个步骤,它直接使用string的复制构造函数将firstname初始化为fn。

程序清单13.3使用了这个类。

程序清单13.3 usett0.cpp

// usett0.cpp -- using a base class
#include <iostream>
#include "tabtenn0.h"
int main ( void )
{
    using std::cout;
    TableTennisPlayer player1("Chuck", "Blizzard", true);
    TableTennisPlayer player2("Tara", "Boomdea", false);
    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;
}

下面是程序清单13.1~程序清单13.3组成的程序的输出:

Blizzard, Chuck: has a table.
Boomdea, Tara: hasn't a table.

注意到该程序实例化对象时将C-风格字符串作为参数:

TableTennisPlayer player1("Chuck", "Blizzard", true);
TableTennisPlayer player2("Tara", "Boomdea", false);

但构造函数的形参类型被声明为const string &。这导致类型不匹配,但与第12章创建的String类一样,string类有一个将const char 作为参数的构造函数,使用C-风格字符串初始化string对象时,将自动调用这个构造函数。总之,可将string对象或C-风格字符串作为构造函数TableTennisPlayer的参数;将前者作为参数时,将调用接受const string &作为参数的string构造函数,而将后者作为参数时,将调用接受const char 作为参数的string构造函数。