c++ - 如何在 C++ 中的派生类的构造函数中初始化基类的 const 变量?

标签 c++ inheritance constructor constants

我有一个没有构造函数的抽象 C++ 类。它应该是一个基类,以便其他类可以继承它。我要做的是在基类中声明一个常量变量并在每个派生类的构造函数中初始化它,但在每个类中都没有。它在 C++ 中合法吗?如果是这样,我该怎么做?

最佳答案

Is it legal in C++?

没有。常量必须在基类构造函数中初始化。

解决方案是在您的基类中提供适当的构造函数——否则无法使用。此外,没有理由不提供该构造函数。

class Base {
    int const constant;
public:
    virtual ~Base() = 0; // Makes this an abstract base class.
protected:
    Base(int c) : constant(c) { }
};

// Must be implemented!
Base::~Base() { }

class Derived : public Base {
public:
    Derived() : Base(42) { }
};

关于c++ - 如何在 C++ 中的派生类的构造函数中初始化基类的 const 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3904759/

相关文章:

c++ - 以编程方式在 C++ 中查找最大静态数组大小

javascript - 为什么不调用原型(prototype)中声明的函数?

c++ - 从模板类继承繁琐

java - 默认构造函数链接

javascript - Typescript 对象的构造函数中 Object.assign() 的目的是什么?

c++ - 如何在opencv c++中画两点之间的线

android - arm-linux-androideabi编译器使用方法

mysql - 使用 Symfony2 更新鉴别器列 Doctrine2

c++ - 为什么我们不能在 C++ 的复制构造函数中使用指针传递?

c++ - Gnome Shell 在使用多个屏幕时导致 QMenu 显示在错误的位置