c++抽象基类私有成员
只是想要一些澄清。 抽象基类不应该有私有成员吗?例如,
class abc{
public:
virtual void foo()=0;
private:
int myInt;
}
您永远无法访问 myInt,因为您无法创建 abc 的实例,并且由于它是私有的,因此它不会位于派生类中。 是否存在在抽象基类中使用私有成员的情况,或者这是错误的?
Just wanted some clarification.
Should abstract base classes never have private members? For example
class abc{
public:
virtual void foo()=0;
private:
int myInt;
}
you can never access myInt since you cannot create an instance of abc and it will not be in a derived class since its private.
Is there any situation where you would use private members in abstract base classes or is this just wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
在 C++ 中,您可以拥有一个具有非纯虚方法的抽象类。在这种情况下,根据设计,拥有私有成员是有意义的:
该代码确保从基类派生的每个对象都有一个名称,该名称在构造期间设置,并且在对象的生命周期内永远不会更改。
编辑:在查尔斯·贝利在他的 答案
您还可以定义纯虚拟函数,在这种情况下,私有属性也有意义:
In C++ you can have an abstract class that has non pure virtual methods. In that case, and depending on the design it can make sense to have private members:
That code ensures that every object that derives from base has a name, that is set during construction and never changes during the lifetime of the object.
EDIT: For completion after Charles Bailey reminded me of it in his answer
You can also define pure-virtual functions, and in that case, private attributes could also make sense:
通常不建议在抽象类中包含数据成员,但您的示例在技术上没有任何问题。在可公开访问的
foo
的实现中,您可以将myInt
用于您喜欢的任何目的。例如:
输出:
It's normally not advisable to have data members in an abstract class but there is nothing technically wrong with your example. In the implementation of
foo
, which is publicly accessible you can usemyInt
for whatever purposes you like.For example:
Output:
并非抽象基类中的所有方法都必须是纯虚拟的。您可能有一些对所有子类都有用的方法。因此,如果基类中有一些修改内部状态的功能,那么您将拥有这些功能的私有成员。
Not all methods in an abstract base class must be pure virtual. You might have some methods which are useful to all subclasses. Thus if you have some functionality in the base class which is modifying internal state you would have private members for those.
如果您使用模板方法设计模式(实现开放/封闭原则),抽象基类拥有
私有
成员是很常见的。If you use the Template Method design pattern (to implement the open/closed principle), it is quite common to have
private
members of an abstract base class.就目前情况而言,你的例子没有任何意义。
然而,抽象基类允许有成员函数定义,而成员函数定义又允许访问基类中的私有成员数据。
As it stands, your example makes no sense.
However, abstract base classes are allowed to have member function definitions, which in turn are allowed to access private member data in the base class.
您可以通过这种快捷方式访问私人会员
代码是 PHP
You can access Private Members through this shortcut way
Code is in PHP