我想声明字符串常量,这些常量将在项目中的多个类中使用。我考虑了两种选择。
选项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";
};
想知道哪种实现方法更好。
已经看过:
更新:
选项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;}
}
我将头文件包含在需要使用常量的位置。这种实现方式有什么明显的缺点吗?
extern
是严格可选的,因此两种方式都可以正常工作。但是你不需要使用new
。{ static string str( "blah" ); return str; }
是通常的方法。 - Potatoswatter