首页 > 文章列表 > C++ 成员函数的继承规则

C++ 成员函数的继承规则

继承 c++
115 2024-04-23

C++ 成员函数继承规则:公有继承:派生类公有继承基类的成员函数,则派生类的成员函数也为公有。保护继承:派生类保护继承基类的成员函数,则派生类的成员函数为保护的。私有继承:派生类私有继承基类的成员函数,则派生类的成员函数为私有的,派生类本身无法直接访问。

C++ 成员函数的继承规则

C++ 成员函数的继承规则

在 C++ 面向对象编程中,类可以通过继承的方式从基类继承数据成员和成员函数。对于成员函数的继承,遵循以下规则:

  • 公有继承:派生类公有继承基类的成员函数,则派生类的成员函数也为公有。
  • 保护继承:派生类保护继承基类的成员函数,则派生类的成员函数为保护的。
  • 私有继承:派生类私有继承基类的成员函数,则派生类的成员函数为私有的,派生类本身无法直接访问。

实战案例:

考虑以下示例:

class Shape {
public:
    virtual double getArea();  // 抽象函数
};

class Rectangle : public Shape {
public:
    Rectangle(double length, double width);
    double getArea() override;  // 重写父类的 getArea 函数
private:
    double length;
    double width;
};

class Square : protected Shape {
public:
    Square(double side);
    double getArea() override;
private:
    double side;
};

class Circle : private Shape {
public:
    Circle(double radius);
    double getArea() override;
private:
    double radius;
};

在这个例子中:

  • Rectangle 类公有继承 Shape 类,因此 getArea 函数在 Rectangle 类中也是公有的。
  • Square 类保护继承 Shape 类,因此 getArea 函数在 Square 类中也是保护的。
  • Circle 类私有继承 Shape 类,因此 getArea 函数在 Circle 类中是私有的。

注意:

  • 抽象函数必须在派生类中重写。
  • 派生类的成员函数可以访问基类的保护和私有数据成员,但只能调用基类的公有和保护成员函数。
  • 派生类的构造函数和析构函数不会从基类继承。