C++继承权限与访问控制详解
下面是对这段 C++ 代码的详细解释,并附上中文注释说明每个部分的作用和意义。
#include <iostream>
using namespace std;// 基类,父类
class Vehicle { // 抽象交通工具类,作为其他具体车辆类的基类
public:string type; // 类型(如卡车、自行车等)string country; // 制造国家string color; // 颜色double price; // 价格int numOfWheel; // 轮子数量protected:int protectedData; // 受保护成员变量,只能在本类及其派生类中访问private:int privateData; // 私有成员变量,只能在Vehicle类内部访问public:void run() {cout << "车跑起来了" << endl;}void stop(); // 声明一个函数,但未定义(仅声明)
};// 私有继承测试:TestClass 私有继承 Vehicle
class TestClass : private Vehicle {
public:void testFunc() {price = 10; // 基类的公有数据被私有继承后,在派生类中变为私有权限// 所以只能在派生类内部使用}
};// 保护继承测试:Truck 保护继承 Vehicle
class Truck : protected Vehicle {
public:void testFunc() {type = "数据测试"; // 基类的 public 成员在 protected 继承下变成 protected 权限protectedData = 10; // 基类的 protected 成员在 protected 继承下仍为 protected// privateData = 10; // 错误!基类的 private 成员无法被访问,无论哪种继承方式}
};// 公有继承测试:Bickle 公有继承 Vehicle
class Bickle : public Vehicle {
public:void testFunc() {protectedData = 10; // 可以访问 protected 成员}
};// 派生类,子类
class Roadster : public Vehicle { // 跑车类,继承自 Vehicle
public:int stateOfTop; // 是否敞篷(例如:0=关闭,1=打开)void openTopped() {// 实现敞篷功能}void pdrifting() {// 实现漂移功能}
};int main() {TestClass test;// test.price = 3.3; // 报错:因为 TestClass 是私有继承 Vehicle,// 所以 price 在外部不可见Truck t;// t.type = "测试"; // 报错:因为 Truck 是保护继承 Vehicle,// 所以 type 变成了 protected,外部不能访问// t.protectedData = 10; // 报错:同理,protectedData 也是 protected,外部不能访问Roadster ftype;ftype.type = "捷豹Ftype"; // 正确:Roadster 公有继承 Vehicle,type 是 publicftype.run(); // 正确:调用从 Vehicle 继承来的 run 函数Bickle bike;bike.type = "死飞"; // 正确:Bickle 公有继承,type 是 publicbike.run(); // 正确:调用 run()return 0;
}
📌 总结:继承权限与访问控制的关系
继承方式 | 基类 public 成员 | 基类 protected 成员 | 基类 private 成员 |
---|---|---|---|
public | public | protected | 不可访问 |
protected | protected | protected | 不可访问 |
private | private | private | 不可访问 |
✅ 关键点总结:
private
成员在任何情况下都不能被派生类或外部访问。- 继承方式决定了基类成员在派生类中的访问级别。
- 公有继承是面向对象中最常用的继承方式,保留了基类成员的访问权限。
- 私有继承会将所有基类成员变为私有,只允许派生类内部使用。
- 保护继承会将基类成员设为受保护,只能在派生类及其子类中访问。
如果你希望进一步了解虚继承、多态、抽象类等内容,也可以继续提问 😊