包含std :: string常量的类 [英] Class containing Constants of std::string
问题描述
因此,我目前正在使用C ++进行学校项目,但我并不十分熟悉。
我想创建一个包含所有常量(字符串,int,double,own类)的类
我正在尝试执行此操作,在Java中一直对我有用:
So I'm currently working on a school-project with C++, which I'm not really familiar with. I would like to create a class, containing all my constants (string,int,double,own classes) I was trying this, which has always worked for me in 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 ++中,出现以下错误:
In C++, however, I get the following error:
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
那么我有什么办法可以存储例如String-Constants这样的东西?
如果是,还有更好的方法吗?如果没有,还有其他方法(#define?)吗?
So is there any way for me to store for example String-Constants like this? If yes, is there even a better way to do it? If no, is there another way (#define?) ?
推荐答案
在C ++ 17,如果使用内联constexpr std :: string_view
,则是定义字符串常量的推荐方法。示例:
In C++17, the recommended way of defining string constants if by using an inline constexpr std::string_view
. Example:
namespace reference
{
inline constexpr std::string_view deepSeaPath{R"(something)"};
// ...
}
这很棒,因为:
-
std :: string_view
是轻量级的无所有权包装器,可以高效地进行包装
std::string_view
is a lightweight non-owning wrapper that can efficiently refer to string literals without any additional costs.
std :: string_view
与<$ c无缝地互操作$ c> std :: string 。
将变量定义为 inline
防止ODR问题。
Defining the variables as inline
prevents ODR issues.
将变量定义为 constexpr
可使编译器和其他用户清楚地知道开发人员认为这些是在编译时已知的常量。
Defining the variables as constexpr
makes it clear to both the compiler and other developers that these are constants known at compile-time.
如果您没有使用C ++ 17的奢侈,这是C ++ 11的解决方案:在名称空间中将常量定义为 constexpr const char *
:
If you do not have the luxury of using C++17, here's a C++11 solution: define your constants as constexpr const char*
in a namespace:
namespace reference
{
constexpr const char* deepSeaPath{R"(something)"};
// ...
}
这篇关于包含std :: string常量的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!