問題描述
C++ 類中的 private
和 protected
成員有什么區別?
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模板網!