——派生类需要自己的构造函数。
派生类可以根据需要添加额外的数据成员和成员函数。
class RatedPlayer : public TableTennisPlayer { private: unsigned int rating; // add a data member 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; } // add a method void ResetRating (unsigned int r) { rating = r; } // add a method };
构造函数必须给新成员和继承的成员提供数据。
RatedPlayer::RatedPlayer(unsigned int r, const string &fn, const string &ln, bool ht) : TableTennisPlayer(fn, ln, ht) { rating = r; }
派生类对象过期时,程序将首先调用派生类析构函数,然后再调用基类析构函数。
要使用派生类,程序必须要能访问基类声明。
派生类对象可以使用基类的方法,条件是方法不是私有的(即公有和保护)。
基类指针可以在不进行显示类型转换的情况下指向派生类对象;基类引用可以在不进行显示类型转换的情况下引用派生类对象
RatedPlayer rplayer(1140, "Mallory", "Duck", true); TableTennisPlayer &rt = rplayer; TableTennisPlayer *pt =&rplayer; rt.Name(); // invoke Name() with reference pt->Name(); // invoke Name() with pointer
不可以将基类对象和地址赋给派生类引用和指针。
---
原文:https://www.cnblogs.com/suui90/p/13172391.html