【问题标题】:C++ Initialize base class' const int in derived class?C ++在派生类中初始化基类的const int?
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

    • 什么?!?我做 C++ 已经有 3 到 4 年了,但我从来没有遇到过这种情况?我一直认为我必须使用默认构造函数...谢谢老兄,马上接受。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2019-01-25
      • 2020-08-19
      • 1970-01-01
      • 2011-04-23
      • 2022-12-03
      • 1970-01-01
      • 1970-01-01
      • 2010-11-10
      • 2016-06-29
      相关资源
      最近更新 更多