首页 > 编程语言 > 详细

C++ 继承特性

时间:2020-06-21 15:09:10      阅读:86      评论:0      收藏:0      [点我收藏+]

——派生类需要自己的构造函数。

    派生类可以根据需要添加额外的数据成员和成员函数。

 

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;
}
  • 派生类构造函数必须使用基类构造函数,创建派生类对象时,程序首先创建基类对象(初始化继承的数据成员)然后再调用派生类构造函数。C++使用成员初始化列表语法完成该操作。
  • 如没有调用基类构造函数,那么将隐式调用基类的默认构造函数。除非要使用默认构造函数,否则应显示调用正确的基类构造函数。

  派生类对象过期时,程序将首先调用派生类析构函数,然后再调用基类析构函数。

  要使用派生类,程序必须要能访问基类声明。

  派生类对象可以使用基类的方法,条件是方法不是私有的(即公有和保护)。

  基类指针可以在不进行显示类型转换的情况下指向派生类对象;基类引用可以在不进行显示类型转换的情况下引用派生类对象

RatedPlayer rplayer(1140, "Mallory", "Duck", true);
TableTennisPlayer &rt = rplayer;
TableTennisPlayer *pt =&rplayer;
rt.Name();    // invoke Name() with reference
pt->Name();    // invoke Name() with pointer

 

 

  不可以将基类对象和地址赋给派生类引用和指针。

  

 

 

  ---

C++ 继承特性

原文:https://www.cnblogs.com/suui90/p/13172391.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!