所以我目前正在使用 C++ 进行一个学校项目,我对此并不熟悉。
我想创建一个类,包含我所有的常量(字符串,整数,双精度,自己的类)
我正在尝试这个,这在 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";
};
然而,在 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
那么有什么方法可以让我存储这样的字符串常量吗?
如果是,还有更好的方法吗?如果没有,还有其他方法吗(#define?)?
在 C++17 中,定义字符串常量的推荐方法是使用inline constexpr std::string_view
。例子:
namespace reference
{
inline constexpr std::string_view deepSeaPath{R"(something)"};
// ...
}
这很棒,因为:
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)"};
// ...
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)