inheritance
在 C++ 中,继承是一种面向对象编程的特性,答应一个类(称为子类或派生类)从另一个类(称为基类或父类)那边继承属性和行为。通过继承,子类可以得到父类的数据成员和成员函数,从而可以重用父类的代码并扩展其功能。如许可以提高代码的复用性和可维护性,同时也符合面向对象编程的封装和抽象特性。
一个B类继承于A类,或称从类A派生类B。如许的话,类A成为基类(父类), 类B成为派生类(子类)。
派生类中的成员,包罗两大部分:
- 类是从基类继承过来的,一类是自己增加的成员。
- 从基类继承过过来的表现其共性,而新增的成员体现了其个性。
简单的类派生
- #CLUB.h
- #ifndef CLUB_H
- #define CLUB_H
- using namespace std;
- #include<iostream>
- #include<string>
- class ProgramCLub {
- private:
- string firstname;
- string lastname;
- bool haveLaptop;
- public:
- ProgramCLub(const string &fname = "None", const string &lname = "None", bool haveLap = false);
- /*const string &fname 和 const string &lname 是引用参数,
- 它们允许函数通过引用来操作传入的实参,而不是进行值的拷贝。
- 使用引用参数可以减少内存消耗和提高性能,特别是在传递大型对象时。*/
- void name() const;
- bool HaveLaptop() const { return haveLaptop; };
- void Reset(const bool v) { haveLaptop = v; };
- };
- #endif // !CLUB_H
复制代码 [code]# program.cpp#include#include "club.h"using namespace std rogramCLub: rogramCLub(const string& fname, const string& lname, bool hl) : firstname(fname), lastname(lname), haveLaptop(hl) {}void ProgramCLub::name() const{ cout |