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;
};



腾讯云 12-20 广告

