简体   繁体   English

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

[英]C++ Initialize base class' const int in derived class?

I have a constant int variable in my base class, and I would like to initialize responding one in my derived class, with different value (taken as a parameter), is this possible? 我的基类中有一个常量int变量,我想在我的派生类中初始化响应一个,具有不同的值(作为参数),这可能吗?

Here's what I did: 这是我做的:

// 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;
};

But obviously it's asking me for Base::Base() which doesn't exist, and if I define it, I will have to give default value for m_index , which I don't want to do. 但显然它要求我不存在Base::Base() ,如果我定义它,我将不得不为m_index提供默认值,我不想这样做。 Do I have to define const int m_index separately in every derived class? 我是否必须在每个派生类中单独定义const int m_index

Similiar question, but I'm not sure if the static affects this in any way: C++ : Initializing base class constant static variable with different value in derived class? 类似的问题,但我不确定静态是否会以任何方式影响它: C ++:在派生类中使用不同的值初始化基类常量静态变量?

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

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

You can call the base constructor like this: 您可以像这样调用基础构造函数:

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;
  }
};

Since c++11 your can even use constructors of the same class. 从c ++ 11开始,你甚至可以使用同一类的构造函数。 The feature is called delegating constructors. 该功能称为委托构造函数。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM