如何在头文件中定义const static std :: string? [英] How can you define const static std::string in header file?
问题描述
我有一个类,我想存储一个静态 std :: string
是真正的const或有效的const通过getter。
我尝试过几种直接方法
1.
const static std :: string foo =bar
2。
const extern std :: string foo ; //定义在标题底部,如
... //标题中剩余的代码
}; //关闭头类声明
std :: string MyClass :: foo =bar
/#endif // MYCLASS_H
我也尝试过
3。
:
static std :: string foo;
public:
static std :: string getFoo(){return foo; }
这些方法分别因为这些原因而失败:
- 错误:静态数据成员的类初始化
非字符类型的常量字符串MyClass :: foo
>
- 为
foo
指定的存储类 - 似乎不喜欢组合extern
与const
或static
- 许多未定义的引用我的代码的其他部分甚至getter函数的返回行
原因具有在头部而不是源文件中的声明。这是一个将被扩展的类,所有其他函数都是纯虚函数,所以我目前没有其他的理由比这些变量有一个源文件。
这是做什么的?
解决方案一个方法是定义一个方法,
例如:
class YourClass
{
public:
//其他东西...
const std :: string& GetString()
{
//初始化静态变量
static std :: string foo(bar);
return foo;
}
//其他东西...
};
这只会初始化静态字符串一次,每次调用函数都会返回一个常量引用变量。有用于您的目的。
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.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
I've also tried
3.
protected: static std::string foo; public: static std::string getFoo() { return foo; }
These approaches fail for these reasons respectively:
- 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.
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.
这篇关于如何在头文件中定义const static std :: string?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!