且构网

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

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

更新时间:2023-02-15 15:19:13

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

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.

在问题背景下使用任何有意义的方法.只要有可能,您就应该尝试使成员成为私有成员,以减少耦合并保护基类的实现,但是,如果那不可能,那么请使用受保护的成员.查看 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.