继承格式
class A :parent B
{
}
派生类要有自己的构造函数
可以根据需要添加额外的数据成员和成员函数
继承的例子:
tabtenn1.h
#ifndef TABTENN1_H_
#define TABTENN1_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;}
};
class RatedPlayer : public TableTennisPlayer
{
private:
unsigned int rating;
public:
RatedPlayer (unsigned int r = 0, const string & fn = "none",
const string & ln = "none", bool ht = false);
RatedPlayer (unsigned int r, const TableTennisPlayer & tp);
unsigned int Rating() const { return rating;}
void ResetTable (unsigned int r) {rating = r;}
};
#endif
tabtenn1.cpp
#include "tabtenn1.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;
}
RatedPlayer::RatedPlayer(unsigned int r, const string & fn,
const string & ln, bool ht) : TableTennisPlayer(fn, ln, ht)
{
rating = r;
}
RatedPlayer::RatedPlayer(unsigned int r, const TableTennisPlayer & tp)
: TableTennisPlayer(tp), rating(r)
{
}
usett1.cpp
#include <iostream>
#include "tabtenn1.h"
int main(void)
{
using std::cout;
using std::endl;
TableTennisPlayer player1("Tara", "Boomdea", false);
RatedPlayer rplayer1(1140, "Mallory", "Duck", true);
rplayer1.Name();
if (rplayer1.HasTable())
cout << ": has a table.\n";
else
cout << ": hasn't a table.\n";
player1.Name();
if (player1.HasTable())
cout << ": has a table";
else
cout << ": hasn't a table.\n";
cout << "Name: ";
rplayer1.Name();
cout << "; Rating: " << rplayer1.Rating() << endl;
RatedPlayer rplayer2(1212, player1);
cout << "Name: ";
rplayer2.Name();
cout << "; Rating: " << rplayer2.Rating() << endl;
return 0;
}
其他:
派生类可以用非私有的基类方法
基类指针或引用可以自动转换成指向派生类的对象。 BUT 基类指针或引用依然只能使用基类的函数 而不能调用派生类的自己的函数
不能反过来 也就是说 不能将基类对象的指针或引用赋值给派生类的指针或引用
关于将派生类对象传递给基类对象初始化
也就是说 派生类传递到基类对象中进行初始化 编译器会调用相应的复制构造函数 然后将基类涉及到的形参传递过去。不涉及的就丢给派生类的构造函数去处理。
完结