【发布时间】:2012-11-27 19:49:01
【问题描述】:
我的基类中有一个常量 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?
【问题讨论】:
标签: c++ class constants derived-class