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++ 成员函数的继承规则的详细内容,更多请关注编程网其它相关文章!
--结束END--
本文标题: C++ 成员函数的继承规则
本文链接: https://www.lsjlt.com/news/605823.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
2024-05-24
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0