[英]How can you define const static std::string in header file?
I have a class that I would like to store a static std::string
that is either truly const or effectively const via a getter. 我有一个类,我想存储一个静态
std::string
,它是真正的const或有效的const通过getter。
I've tried a couple direct approaches 我尝试了几种直接的方法
1. 1。
const static std::string foo = "bar";
2. 2。
const extern std::string foo; //defined at the bottom of the header like so
...//remaining code in header
}; //close header class declaration
std::string MyClass::foo = "bar"
/#endif // MYCLASS_H
I've also tried 我也试过了
3. 3。
protected:
static std::string foo;
public:
static std::string getFoo() { return foo; }
These approaches fail for these reasons respectively: 这些方法分别因以下原因而失败:
const string MyClass::foo
of non-literal type const string MyClass::foo
的类内初始化非文字类型的const string MyClass::foo
foo
-- it doesn't seem to like combining extern
with const
or static
foo
指定的存储类 - 它似乎不喜欢将extern
与const
或static
结合起来 The reason I would like to have the declaration within the header rather than source file. 我想在头文件而不是源文件中使用声明的原因 。 This is a class that will be extended and all its other functions are pure virtual so I currently have no other reason than these variables to have a source file.
这是一个将被扩展的类,它的所有其他函数都是纯虚拟的,所以我目前除了这些变量之外没有其他原因来拥有源文件。
So how can this be done? 那么怎么做呢?
One method would be to define a method that has a static variable inside of it. 一种方法是定义一个在其中具有静态变量的方法。
For example: 例如:
class YourClass
{
public:
// Other stuff...
const std::string& GetString()
{
// Initialize the static variable
static std::string foo("bar");
return foo;
}
// Other stuff...
};
This would only initialize the static string once and each call to the function will return a constant reference to the variable. 这只会初始化静态字符串一次,每次调用该函数都会返回对该变量的常量引用。 Useful for your purpose.
对你有用。
You can only initialize a static const value in the constructor for integer types, not other types. 您只能在构造函数中为整数类型而不是其他类型初始化静态const值。
Put the declaration in the header: 将声明放在标题中:
const static std::string foo;
And put the definition in a .cpp file. 并将定义放在.cpp文件中。
const std::string classname::foo = "bar";
If the initialization is in the header file then each file that includes header file will have a definition of the static member. 如果初始化在头文件中,那么包含头文件的每个文件都将具有静态成员的定义。 There will be linker errors as the code to initialize the variable will be defined in multiple .cpp files.
将会出现链接器错误,因为初始化变量的代码将在多个.cpp文件中定义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.