所以我目前正在与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:developmentc++bio-sim-qtbio-sim-qtReference.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)"};
// ...
}
您应该在头文件中声明数据成员,但定义应放在源文件中,例如:
const std::string Reference ::earthPath = "E:\Development\C++\Material\terrain\deep_sea.tga";
有关详细信息,请参阅:静态数据成员初始化。
PS:类不用于将其数据成员公开到公共范围内。而是使用 Getter 和 Setter 函数,而数据成员不在公共范围内。如果您只需要数据成员,那么命名空间可能是比类更好的设计选择。