且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C++ 类的私有成员和受保护成员之间有什么区别?

更新时间:2022-02-21 22:54:27

私有成员只能在定义它们的类中访问.

Private members are only accessible within the class defining them.

受保护成员可以在定义它们的类中以及从该类继承的类中访问.

Protected members are accessible in the class that defines them and in classes that inherit from that class.

它们的类的朋友也可以访问它们,在受保护成员的情况下,它们的派生类的朋友也可以访问.

Both are also accessible by friends of their class, and in the case of protected members, by friends of their derived classes.

编辑 2:使用在您的问题上下文中有意义的任何内容.您应该尽可能将成员设为私有,以减少耦合并保护基类的实现,但如果不可能,则使用受保护的成员.查看 C++ 常见问题 以更好地了解该问题.这个关于受保护变量的问题也可能有所帮助.

Edit 2: Use whatever makes sense in the context of your problem. You should try to make members private whenever you can to reduce coupling and protect the implementation of the base class, but if that's not possible then use protected members. Check C++ FAQ for a better understanding of the issue. This question about protected variables might also help.