C++在派生类中初始化基类的const int?

标签 c++ class constants derived-class

我的基类中有一个常量 int 变量,我想在我的派生类中用不同的值(作为参数)初始化响应变量,这可能吗?

这是我做的:

// Base.h (methods implemented in Base.cpp in the actual code)
class Base {
    public:
        Base(const int index) : m_index(index) {}
        int getIndex() const { return m_index; }
    private:
        const int m_index;
};

// Derived.h
class Derived : public Base {
    public:
        Derived(const int index, const std::string name) : m_name(name) {}
        void setName(const std::string name) { m_name = name; }
        std::string getName() const { return m_name; }
    private:
        std::string m_name;
};

但显然它要求我提供不存在的 Base::Base(),如果我定义它,我将不得不为 m_index 提供默认值,我不想这样做。我是否必须在每个派生类中分别定义 const int m_index

类似的问题,但我不确定静态是否会以任何方式影响此问题: C++ : Initializing base class constant static variable with different value in derived class?

最佳答案

只需在 Derived 的初始化列表中调用适当的 Base 构造函数:

Derived(const int index, const std::string name) : Base(index), m_name(name) {}

关于C++在派生类中初始化基类的const int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13591886/

相关文章:

c++ - 当#define 在 #if 中时, token "#"错误之前缺少二元运算符

c++ - 如何命名我的新项目的命名空间?

javascript - ES6 - 使用 import 语句在类上声明原型(prototype)方法

c++ - 为什么我们说#define Processor 在程序中创建多个拷贝?

c# - 如何继承父常量并访问它们?

c++ - 如何组合 lambda、可变参数函数和函数指针?

c++ - Windows 上的柯南声明设置未设置,已设置

PHP::完全限定方法文字到字符串

c++ - 不能在另一个类中声明类

c++ - 如何在现代 C++ 中使用生成器初始化 const 容器?