[英]Private and Protected Members
I'm having trouble understanding the difference between private and protected members in a C++ class. 我在理解C ++类中私有成员和受保护成员之间的区别时遇到了麻烦。 In simple terms, what is the difference?
简单来说,有什么区别?
protected
members are accessible by derived classes. protected
成员可通过派生类访问。 private
members are not. private
成员不是。
Generally (most of the time) members should either be private
or public
. 通常(大多数情况下)成员应为
private
或public
成员。 It is rare and unusual to need a protected
member (edit) in a well-designed system. 在精心设计的系统中需要
protected
成员(编辑)是很少见且不寻常的。
Maybe I should elaborate on why protected
members can be a code-smell. 也许我应该详细说明为什么
protected
成员可以成为代码气味。
If derived classes have access to data members that other classes do not, this could be an indication that the base & derived classes are too tightly coupled. 如果派生类可以访问其他类不能访问的数据成员,则可能表明基类和派生类之间的耦合太紧密。 The derived classes have access to the base class' state, and therefore the base class' state is subject to corruption.
派生类可以访问基类的状态,因此基类的状态容易损坏。 If this were not the case, then there's also often no reason to just make the data members
public
. 如果不是这种情况,那么通常也没有理由仅
public
数据成员。
Others have gone in to greater detail on this. 其他人对此进行了更详细的介绍。
Here is what Stroustrup says in his text: 这是Stroustrup在其案文中所说的:
Members declared protected are far more open to abuse than members declared private .
被宣布为受保护成员比被宣布为私有成员更容易受到虐待。 In particular, declaring data members protected is usually a design error.
特别是,声明受保护的数据成员通常是设计错误。 Placing significant amounts of data in a common class for all derived classes to use leaves that data open to corruption.
将大量数据放置在公共类中以供所有派生类使用,这些数据容易遭到破坏。 Worse, protected data, like public data, cannot easily be restructured because there is no good way of finding every use.
更糟糕的是,受保护的数据(如公共数据)无法轻松地进行重组,因为没有找到每种用途的好方法。 Thus, protected data becomes a software maintenance problem.
因此,受保护的数据成为软件维护问题。
See also this question . 另请参阅此问题 。
Protected members can be accessed by derived classes (and friends). 派生的类(和朋友)可以访问受保护的成员。
Private members can only be accessed by the declaring class (or by friends). 私有成员只能由声明类(或朋友)访问。
Simple example: 简单的例子:
class Base
{
protected:
int prot;
private:
int priv;
public:
int Prot() const { return prot; }
int Priv() const { return priv; }
};
class Derived
{
public:
void ShowProt() { cout << prot; } // OK - prot is accessible because it is protected
void ShowPriv() { cout << priv; } // Compile Error - cannot access priv, which is private
void ShowPriv2() { cout << Priv(); } // OK, because Priv() is public
};
From the C++ FAQ : 从C ++常见问题解答 :
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.