在C++类中,public和private是访问说明符,用于控制成员变量和函数对程序中其他部分的可见性。这里是一个使用"龙珠"系列的简化示例,以说明它们之间的区别:
class DragonBallCharacter {
public:
// 公有成员可以从类外部访问
std::string name;
int powerLevel;
DragonBallCharacter(std::string characterName, int initialPowerLevel) : name(characterName), powerLevel(initialPowerLevel) {}
// 公有方法用于显示角色信息
void displayInfo() {
std::cout << name << " 的力量级为 " << powerLevel << std::endl;
}
private:
// 私有成员只能在类内部访问.
bool isSuperSaiyan = false;
// 私有方法用于变身为超级赛亚人
void transformSuperSaiyan() {
isSuperSaiyan = true;
powerLevel *= 50; // 大幅增加力量级
}
};
int main() {
DragonBallCharacter goku("孙悟空", 9000);
// 从类外部访问公有成员
goku.displayInfo(); // 悟空的力量级为9000
// 尝试访问私有成员将导致编译错误
// goku.transformSuperSaiyan(); // 错误:在此上下文中 transformSuperSaiyan 是私有的
return 0;
}
成员访问说明符:
- public:public成员可以在类内部和类生成的对象中访问。其他类和函数也可以访问public成员
- protected:protected成员只能在类内部和派生类中访问。派生类是指从基类派生出的子类。其他类和函数无法访问protected成员。
- private:private成员只能在类内部访问,包括类的成员函数和其他private成员。类生成的对象和派生类都无法访问private成员。