3 回答

TA貢獻1797條經(jīng)驗 獲得超4個贊
您必須在類定義之外定義靜態(tài)成員并在那里提供初始化程序。
第一
// In a header file (if it is in a header file in your case)
class A {
private:
static const string RECTANGLE;
};
接著
// In one of the implementation files
const string A::RECTANGLE = "rectangle";
您最初嘗試使用的語法(類定義中的初始化程序)僅允許使用整數(shù)和枚舉類型。
從C ++ 17開始,您有另一個選項,它與您的原始聲明非常相似:內(nèi)聯(lián)變量
// In a header file (if it is in a header file in your case)
class A {
private:
inline static const string RECTANGLE = "rectangle";
};
無需額外定義。

TA貢獻1827條經(jīng)驗 獲得超9個贊
在類定義中,您只能聲明靜態(tài)成員。它們必須在課堂之外定義。對于編譯時積分常量,標(biāo)準(zhǔn)會使您可以“初始化”成員。但它仍然不是一個定義。例如,如果沒有定義,那么獲取地址是行不通的。
我想提一提,我沒有看到使用的std :: string在為const char []的利益為常數(shù)。std :: string很好,除了它需要動態(tài)初始化。所以,如果你寫的東西像
const std::string foo = "hello";
在命名空間范圍內(nèi),foo的構(gòu)造函數(shù)將在執(zhí)行main啟動之前運行,此構(gòu)造函數(shù)將在堆內(nèi)存中創(chuàng)建常量“hello”的副本。除非你真的需要RECTANGLE成為std :: string,否則你也可以寫
// class definition with incomplete static member could be in a header file
class A {
static const char RECTANGLE[];
};
// this needs to be placed in a single translation unit only
const char A::RECTANGLE[] = "rectangle";
那里!沒有堆分配,沒有復(fù)制,沒有動態(tài)初始化。
干杯,s。
- 3 回答
- 0 關(guān)注
- 738 瀏覽
添加回答
舉報