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 类中是私有的。注意:
以上就是C++ 成员函数的继承规则的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号