私人和受保护的成员:C ++ [英] Private and Protected Members : C++

查看:133
本文介绍了私人和受保护的成员:C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人能告诉我在课堂上私人和受保护的成员之间的区别吗?我理解从最佳实践约定,变量和函数不在类外调用应该被私有 - 但看着我的MFC项目,MFC似乎喜欢受保护。

Can someone enlighten me as to the difference between private and protected members in classes? 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 favour protected.

推荐答案

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

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.

编辑:

编辑2:使用在您的问题的上下文中有意义的任何东西。你应该尝试让成员私有,只要你能减少耦合和保护基类的实现,但如果这是不可能的,那么使用受保护的成员。请查看 C ++常见问题解答Lite ,以便更好地了解问题。 有关受保护变量的这个问题也可能有帮助。

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 Lite for a better understanding of the issue. This question about protected variables might also help.

这篇关于私人和受保护的成员:C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆