为什么纯虚拟/抽象类需要一个构造函数,特别是受保护的const成员变量? [英] Why does a purely virtual/abstract class require a constructor, in particular for protected const member variables?

查看:228
本文介绍了为什么纯虚拟/抽象类需要一个构造函数,特别是受保护的const成员变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个纯虚拟类,定义如下:

I have a purely virtual class defined as such:

class BaseClass {
 protected:
  const int var;
 public:
  void somefun() = 0; // what I mean by a purely virtual class
  // stuff...
};

如果我不添加如下定义的构造函数:

If I don't add a constructor defined as such:

BaseClass(const int & VAR) : var(VAR) {};

,我将不得不在以后的衍生类中使用,我的派生类不能初始化const变量var到它想要的值。现在我实际上明白这里发生了什么。在构造派生类之前,调用基类的构造函数,此时必须初始化const成员变量。我的问题不是一个我如何让我的代码工作这样的问题,这已经做了。我的问题是为什么编译器认为有必要。对于纯虚拟类,我不应该允许写如下:

that I would have to subsequently use in ever derived class, my derived class can't initialize the const variable var to whichever value it wants to. Now I actually understand what's going on here. Before constructing a derived class, a constructor of the base class is called, at which point const member variables must be initialized. My question is not a "how do I make my code work" kind of question, that's already been done. My question is about why the compiler thinks it's necessary. For a purely virtual class, shouldn't I be allowed to write something like:

class DerivedClass : BaseClass {
 public:
  DerivedClass() : var(SOME_VALUE) {};
}

如果编译器知道对BaseClass构造函数的调用必然会调用一些派生类constructror(因为抽象类型的对象永远不能实例化)不应该给我们一点余地吗?

If the compiler knows that a call to a BaseClass constructor will necessarily be followed by a call to some derived class constructror (since an object of abstract type can never be instantiated) shouldn't it give us a bit more leeway?

这是一个结果C ++如何选择解决钻石问题?即使是这样的情况下,编译器应该不是至少在某种程度上允许纯成员函数的const成员变量在派生类中定义的可能性?这是太复杂还是与C ++解决方案的钻石问题混乱?

Is this all a consequence of how C++ chooses to get around the Diamond problem? Even if that was the case, shouldn't the compiler at least somehow allow for the possibility that const member variable of purely virtual functions will be defined in derived classes? Is that too complicated or does that mess with the C++ solution to the Diamond problem?

感谢大家的帮助。

推荐答案

它不是纯虚拟(不管你的意思) - 它包含一个数据成员。

It's not "purely virtual" (whatever you mean by that) - it contains a data member.

只能由该类的构造函数的初始化列表初始化,而不能由派生类初始化。这就是如何指定对象初始化:初始化的所有成员在构造函数主体开始之前初始化。

Class members can only be initialised by the initialiser list of a constructor of that class, not of a derived class. That's how object initialisation is specified: all members that are initialised, are initialised before the constructor body begins.

常量对象必须初始化,因为它们不能被赋值

Constant objects must be initialised, since they can't be assigned a value later.

因此,具有常量数据成员的类必须在每个构造函数中初始化。

Therefore, a class with a constant data member must initialise it in each constructor.

这篇关于为什么纯虚拟/抽象类需要一个构造函数,特别是受保护的const成员变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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