#include <iostream>
#include <string>
class Student {
private:
int id;
protected:
std::string name;
public:
void displayInfo() {
std::cout << "ID: " << id << ", Name: " << name << std::endl;
}
// 构造函数用于初始化成员变量
Student(int i, const std::string& n) : id(i), name(n) {}
};
int main() {
Student s(1, "Alice");
// s.id; // 错误,私有成员不能在类外直接访问
// s.name; // 错误,保护成员不能在类外直接访问
s.displayInfo(); // 可以直接访问,公有成员在类外可访问
return 0;
}
- 直接访问情况:
displayInfo()
可以在 main
函数中直接访问,因为它是公有成员。公有成员提供了类的外部接口,允许其他代码访问和调用该函数。
- 不能直接访问情况:
id
不能在 main
函数中直接访问,因为它是私有成员。私有成员只能在类的内部成员函数中访问,这是为了对类的数据进行封装,防止外部代码随意修改。
name
不能在 main
函数中直接访问,因为它是保护成员。保护成员类似私有成员,但允许派生类访问。在类外(非派生类的代码中)不能直接访问,这也是为了数据的封装和保护。