我的基类中有一个常量 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/