![](/img/trans.png)
[英]How can I initialize a const variable of a base class in a derived class' constructor in C++?
[英]C++ Initialize base class' const int in 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 ++:在派生類中使用不同的值初始化基類常量靜態變量?
只需在Derived
的初始化列表中調用相應的Base
構造函數:
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() {}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.