[英]C++: Initializing class member variable with reference to another class member variable?
我試圖在c ++中創建一個類,以調用以存儲許多參數的值,這些參數被組織為“行星”類和“衛星”類的成員變量,我想通過引用“行星”的實例進行初始化。 在這里,我提供一個示例,其中有一個“ PlanetCatalog”類,其成員變量為“ Planet neptune”和一個“ Satellite triton”。
class Planet {
public:
double a;
Planet() {}
void setParams( const double a_) {
a = a_;
}
};
class Satellite {
public:
double b;
Planet & planet;
Satellite( Planet & planet_):planet(planet_) { }
void setParams(const double b_) {
b = b_;
}
};
class PlanetCatalog {
public:
Planet neptune;
Satellite triton(neptune);
void setAll() {
neptune.setParams(1.);
triton.setParams(2.);
}
};
但是,在編譯時遇到錯誤。
error: unknown type name 'neptune'
Satellite triton(neptune);
是否有可能像我在此處那樣將Planet和Satellite存儲為同一類的變量。 如果不是,那么有人可以建議用c ++更好地組織此功能的方法嗎?
使用括號進行類內初始化使編譯器將triton
視為非靜態成員函數聲明,且neptune
是第一個參數的類型,應改用list-initialization語法:
Satellite triton{neptune};
注意,實際上不需要為此定義PlanetCatalog
構造函數。
發生了什么?
class PlanetCatalog { public: ... Planet neptune; Satellite triton(neptune); //<-- Compiler sees this as a non-static member-function declaration ...
由於該語句的上下文,編譯器將其視為非靜態成員函數聲明,並嘗試在相關的名稱空間中找到名為neptune
類型 ; 由於找不到它,因此發出錯誤。
選項1 :您可以在其member-initialization-list中定義一個構造函數,為您初始化triton
class PlanetCatalog {
public:
...
Planet neptune;
Satellite triton;
PlanetCatalog() : triton(neptune) {}
...
注意:使用此選項, 您的類數據成員的順序很重要 ,因為數據成員的初始化順序是由其在類中的聲明順序定義的,而不是由member-initialization-list
的初始化順序定義的
選項2 :另一個簡單的解決方案是使用復制初始化
Satellite triton = neptune;
選項3 :或列表初始化
Satellite triton{neptune};
選項2和3是可取的,因為它隱式地強制聲明順序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.