C++派生类访问受保护成员:关于FemaleIn类代码的疑问
嘿,结合你的代码场景,我来把C++里派生类访问protected成员的规则讲清楚,你一看就懂~
核心规则梳理
首先得明确protected成员的核心特性:基类的protected成员,只有基类自身和它的派生类可以在类内部直接访问,但有个关键限制——派生类只能访问自己对象的protected基类成员,不能碰其他基类对象的。
另外,继承方式会影响基类protected成员在派生类中的访问权限:
- 用
public继承:基类的protected成员在派生类里依然是protected权限 - 用
protected继承:基类的protected成员在派生类里变成protected - 用
private继承:基类的protected成员在派生类里变成private
结合你的代码场景分析
你的FemaleIn类继承自Female,而Female本身也是派生类。从你写的enterPatientData函数来看,你直接用this->name、this->age这些访问成员,这完全是合法的!
假设你的Female类定义大概是这样(包含protected的成员变量):
#include <iostream> #include <string> using namespace std; // 假设Female是从某个基类派生的,这里简化示例 class Female { protected: string name; int age; string diagnosis; string insuranceName; string insuranceNumber; // 其他成员函数或变量... }; class FemaleIn : public Female { public: void enterPatientData() { cout << "enter name "; cin >> this->name; cout << "enter your age "; cin >> this->age; cout << "enter your diagnosis "; cin >> this->diagnosis; cout << "enter your insurance name "; cin >> this->insuranceName; cout << "enter your insurance number "; cin >> this->insuranceNumber; } };
这里FemaleIn作为Female的派生类,在自己的成员函数enterPatientData里访问this指向的对象的protected成员,完全符合规则——因为这是访问自身对象继承来的protected成员,编译器不会报错。
要避开的坑
如果你尝试在FemaleIn里访问其他Female对象的protected成员,那就是非法的,比如:
class FemaleIn : public Female { public: void printOtherPatient(Female& anotherPatient) { // ❌ 错误!不能访问其他Female对象的protected成员 cout << anotherPatient.name << endl; } };
这种情况编译器会直接报错,因为派生类只能操作自己的那部分继承成员,不能越界访问其他对象的protected成员。
补充:多层继承的情况
因为你提到Female本身也是派生类,比如它继承自Person类:
class Person { protected: string name; int age; }; class Female : public Person { protected: string diagnosis; string insuranceName; string insuranceNumber; };
那FemaleIn作为Female的派生类,依然可以直接访问Person里的name、age,以及Female里的diagnosis等protected成员——只要是访问自身对象的,多层继承下这个规则依然成立。
内容的提问来源于stack exchange,提问作者성기덕

