这个例子我是看懂了,真的看懂了,因为它很简单,不过也有一些可以学习的地方。
第12章我看的有写糊涂,有一些例子就没有实践,有的实践了还出错,后续再研究。
来看看本例:就是一个乒乓球会员类
tabtenn0.h:
#pragma once
#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; };
};
tabtenn0.cpp:
#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;
}
usett0.cpp:(主函数在这里呢)
// Usett0.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include "tabtenn0.h"
int main()
{
// std::cout << "Hello World!\n";
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 .\n";
else
cout << ":hasn't a table .\n";
return 0;
}
运行结果:
Blizzard,Chuck:has a table .
Boomdea,Tara:hasn't a table .
D:\eCode\CPPPrimerPlusCode\Chapter13ClassInheritance\13.1ASimpleBaseClass\Usett0\Debug\Usett0.exe (进程 17340)已退出,代码为 0。
按任意键关闭此窗口. . .
本文展示了C++中一个简单的乒乓球会员类(TableTennisPlayer)的定义和实现,包括类的成员变量、构造函数、访问器和修改器方法。通过一个主函数实例,演示了如何创建会员对象并检查他们是否拥有球桌。

被折叠的 条评论
为什么被折叠?



