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

时间:2023-01-21
本文介绍了C++ 类的私有成员和受保护成员之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C++ 类中的 privateprotected 成员有什么区别?

What is the difference between private and protected members in C++ classes?

我从最佳实践约定中了解到,在类外调用的变量和函数应该设为 private——但是看看我的 MFC 项目,MFC 似乎更喜欢 protected>.

I understand from best practice conventions that variables and functions which are not called outside the class should be made private—but looking at my MFC project, MFC seems to favor protected.

有什么区别,我应该使用哪个?

What's the difference and which should I use?

推荐答案

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

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.

这篇关于C++ 类的私有成员和受保护成员之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:C++:空类的对象的大小是多少? 下一篇:将模板化的 C++ 类拆分为 .hpp/.cpp 文件——这可能

相关文章

最新文章