在派生类中初始化基类的const

在派生类中初始化基类的const

本文介绍了C ++在派生类中初始化基类的const int吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在基类中有一个常量int变量,我想在派生类中初始化一个具有不同值(作为参数)的响应变量,这可能吗?

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?

这就是我所做的:

// 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 吗?

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. Do I have to define const int m_index separately in every derived class?

类似的问题,但我不是确保静电是否以任何方式影响此:

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?

推荐答案

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

Simply call the appropriate Base constructor in the Derived's initialization list:

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

这篇关于C ++在派生类中初始化基类的const int吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 02:43