C++ C++;初始化基类';派生类中的常量int?

C++ C++;初始化基类';派生类中的常量int?,c++,class,constants,derived-class,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; } pri

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

类似的问题,但我不确定静态是否会以任何方式影响这一点:

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

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

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

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() {}

什么?!?我一直做C++ 3到4年之类的事情,我从来没有遇到过这个问题?我一直认为我必须使用默认构造函数。。。谢谢,伙计,我马上就要接受了。