问题描述
提出此问题,因为我觉得以后在派生类中将需要我的基础的成员变量。是否有使他们受到保护的缺点?
Asking this question because I feel that member variables of my base will be needed later in derived classes. Is there a drawback of making them protected?
编辑:编辑以更好地显示我的意图。
Edited to better show my intention.
@sbi:这也错了吗?
@sbi : Is this also wrong?
此类将用于在其他类中进行错误记录和检索。是从它得到还是使用它的对象更好 - 我不知道。但我认为getter和setter方法是这个类是什么。
This class will be used for error recording and retrieving in other classes. Is it better to derive from it or use an object of it - I don't know. But I think the getter and setter methods are what this class is all about.
class ErrorLogger
{
public:
//Making this function virtual is optional
virtual void SetError(const char*, ...);
const char* GetError() const;
protected:
char* z_ErrorBuf;
};
推荐答案
封装是OO的主要特性之一。在类中封装数据意味着类的用户不能打断类的数据的不变量,因为类的状态只能通过它的成员函数来操作。
Encapsulation is one of the main features of OO. Encapsulating your data in classes means that users of the class can not break the class' data's invariants, because the class' state can only be manipulated through its member functions.
如果允许派生类访问其基类的数据,则 派生类需要注意不要使基类的数据不变式 。这引发了窗口外的封装,只是错误。 (所以,BTW。)
If you allow derived classes access to their base class' data, then derived classes need to take care to not to invalidate the base class' data's invariants. That throws encapsulation out of the window and is just wrong. (So do getters and setters, BTW.)
我发现自己使用 protected
越来越少,甚至对于成员函数。如果一个类完全实现了一个简单的概念,那么它的所有状态都应该可以通过它的公共接口进行操作。如果派生类需要后门潜入,那么我通常会问我的设计。 (这不是说我从来不使用 protected
,我只是发现我需要它越来越少。)
I find myself using protected
less and less over the years, even for member functions. If a class fully implements a simple concept, then all of its state should be manipulatable through its public interface. If derived classes need "back doors" to sneak in, then I usually question my design. (Which isn't to say I never use protected
. I just find I need it less and less.)
这篇关于是成功变量保护的好习惯吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!