C ++类的私有成员和受保护成员之间有什么区别? [英] What is the difference between private and protected members of C++ classes?

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

问题描述

C ++类中的 private protected 成员之间有什么区别?

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

我从最佳实践惯例中了解到,不应在类外调用变量和函数,但应将它们设为 private (私有),但是在我的MFC项目中,MFC似乎更倾向于受保护的>.

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.

在问题背景下使用任何有意义的方法.只要有可能,您就应该尝试使成员成为私有成员,以减少耦合并保护基类的实现,但是,如果那不可能,那么请使用受保护的成员.查看 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 ++类的私有成员和受保护成员之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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