如何在头文件中定义 const static std::string?
我有一个类,我想存储一个静态 std::string
,它要么是真正的 const,要么是通过 getter 有效的 const.
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.
我尝试了几种直接方法
1.
I've tried a couple direct approaches
1.
const static std::string foo = "bar";
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
我也试过了
3.
protected:
static std::string foo;
public:
static std::string getFoo() { return foo; }
这些方法分别因以下原因而失败:
These approaches fail for these reasons respectively:
- 错误:非文字类型的静态数据成员
const string MyClass::foo
的类内初始化 - 为
foo
指定的存储类 -- 它似乎不喜欢将extern
与const
或static
- 我的代码的其他部分甚至 getter 函数的返回行都会产生许多未定义的引用"错误
- error: in-class initialization of static data member
const string MyClass::foo
of non-literal type - storage class specified for
foo
-- it doesn't seem to like combiningextern
withconst
orstatic
- many 'undefined reference to' errors generated by other parts of my code and even the return line of the getter function
原因我希望在标头而不是源文件中声明.这是一个将被扩展的类,它的所有其他功能都是纯虚拟的,所以我目前除了这些变量之外没有其他理由拥有源文件.
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.
例如:
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.
相关文章