Awe*_*e36 0 c++ string static const constants
因此,我目前正在使用C ++进行学校项目,而我对此并不十分熟悉。我想创建一个类,其中包含我尝试的所有常量(string,int,double,own类),它在Java中一直对我有用:
class Reference {
//Picture-Paths
public:
static const std::string deepSeaPath = "E:\\Development\\C++\\Material\\terrain\\deep_sea.tga";
static const std::string shallowWaterPath = "E:\\Development\\C++\\Material\\terrain\\deep_sea.tga";
static const std::string sandPath = "E:\\Development\\C++\\Material\\terrain\\deep_sea.tga";
static const std::string earthPath = "E:\\Development\\C++\\Material\\terrain\\deep_sea.tga";
static const std::string rocksPath = "E:\\Development\\C++\\Material\\terrain\\deep_sea.tga";
static const std::string snowPath = "E:\\Development\\C++\\Material\\terrain\\deep_sea.tga";
};
Run Code Online (Sandbox Code Playgroud)
但是,在C ++中,出现以下错误:
Error C2864 'Reference::Reference::earthPath': a static data member with an in-class initializer must have non-volatile const integral type bio-sim-qt e:\development\c++\bio-sim-qt\bio-sim-qt\Reference.hpp 16 1
Run Code Online (Sandbox Code Playgroud)
所以我有什么办法可以存储例如这样的String-Constants吗?如果可以,还有更好的方法吗?如果否,还有其他方法(#define?)吗?
在C ++ 17中,建议的定义字符串常量的方法(如果使用)inline constexpr std::string_view。例:
namespace reference
{
inline constexpr std::string_view deepSeaPath{R"(something)"};
// ...
}
Run Code Online (Sandbox Code Playgroud)
这很棒,因为:
std::string_view 是一个轻量级的无所有权包装器,可以有效地引用字符串文字,而无需任何额外费用。
std::string_view与std::string。无缝互通。
将变量定义为inline可以防止ODR问题。
定义变量constexpr使编译器和其他开发人员都清楚这些是在编译时已知的常数。
如果您不习惯使用C ++ 17,请使用以下C ++ 11解决方案:constexpr const char*在名称空间中定义常量:
namespace reference
{
constexpr const char* deepSeaPath{R"(something)"};
// ...
}
Run Code Online (Sandbox Code Playgroud)