簡體   English   中英

類中的靜態字符串常量與常量的命名空間[c ++]

[英]static string constants in class vs namespace for constants [c++]

我想聲明將在項目中的各個類中使用的字符串常量。 我正在考慮兩種選擇

選項1:

#header file 
class constants{
    static const string const1;
};

#cpp file

const string constants::const1="blah";

選項2:

#header file 
namespace constants{
    static const string const1="blah";
};

只是想知道什么是更好的實現。

已經看過了

在C ++中存儲類特定命名常量的位置

在C ++中放置常量字符串的位置:靜態類成員或匿名名稱空間


更新:

選項3:

根據“potatoswatter”和“sellibitze”的建議,我目前有以下實施方案?

#header file
namespace constants{
    extern const string& const1(); //WORKS WITHOUT THE EXTERN  ***WHY***
};

#cpp file
namespace constants{
   const string& const1(){static string* str = new string ("blah"); return *str;}
}

我包含頭文件,我需要使用常量。 這種實施有什么主要缺點嗎?

2年后更新:

每個可由多個源文件訪問的全局應包含在內inline函數中,以便鏈接器在文件之間共享對象,程序會正確初始化它。

inline std::string const &const1() {
    static std::string ret = "hello, world!";
    return ret;
}

inline函數是隱式extern ,如果你願意,可以包裝在命名的命名空間或類中。 (但是不要只使用一個類來保存靜態成員,因為命名空間更好。並且不要使用匿名命名空間,因為這會破壞鏈接器,並且每個源都會看到不同的std::string對象。)

所有訴諸std::string答案都冒着為字符串文字動態分配內存的風險,該字符串文字將在程序(和二進制文件)的整個生命周期內保持不變,因此應該避免使用它們。

sellibitze的答案很接近,但它有一次聲明它然后在其他地方定義它的問題,我覺得這不是優雅的,而是更多的工作。 最好的方法是

namespace constants {
    const char * const blah = "blah!"
    const char * const yada = "yada yada!"
}

這是解決方案, 這里進一步討論。

都不是。 我會選擇這個:

// header file
namespace constants {
extern const char const1[];
}

// cpp file
namespace constants {
extern const char const1[] = "blah";
}

頭文件包含const1的聲明,其類型不完整但可轉換為char const* ,而cpp-file包含具有外部鏈接的字符數組的定義。 沒有像std::string那樣的動態初始化。 所以,這是一個加號,恕我直言。

選項1與選項2的實現方式相同,但方式更為混亂。

如果您要使用僅具有靜態成員的類,尤其是全局訪問/常量,請使用命名空間。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM