我的基类中有一个常量 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++:在派生类中初始化具有不同值的基类常量静态变量?
只需致电相应的Base
构造函数中的Derived
的初始化列表:
Derived(const int index, const std::string name) : Base(index), m_name(name) {}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)