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

时间:2012-11-27 19:49:02

标签: c++ class const 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?

2 个答案:

答案 0 :(得分:16)

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

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

答案 1 :(得分:1)

您可以像这样调用基础构造函数:

class B1 {
  int b;
public:    
  // inline constructor
  B1(int i) : b(i) {}
};

class B2 {
  int b;
protected:
  B2() {}    
  // noninline constructor
  B2(int i);
};

class D : public B1, public B2 {
  int d1, d2;
public:
  D(int i, int j) : B1(i+1), B2(), d1(i)
  {
    d2 = j;
  }
};

从c ++ 11开始,你甚至可以使用同一类的构造函数。该功能称为委托构造函数。

Derived(){}
Derived(const int index, const std::string name) : Derived() {}
相关问题