【发布时间】:2013-08-01 18:05:14
【问题描述】:
我有一个类,我想存储一个静态 std::string,它要么是真正的 const,要么是通过 getter 有效的 const。
我尝试了几种直接方法
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; }
这些方法分别因以下原因而失败:
- 错误:非文字类型的静态数据成员
const string MyClass::foo的类内初始化 - 为
foo指定的存储类——它似乎不喜欢将extern与const或static结合使用 - 我的代码的其他部分甚至 getter 函数的返回行都会产生许多“未定义的引用”错误
原因我希望在标头而不是源文件中声明。这是一个将被扩展的类,它的所有其他功能都是纯虚拟的,所以除了这些变量之外,我目前没有其他理由拥有源文件。
那么如何做到这一点呢?
【问题讨论】:
-
查看stackoverflow.com/questions/1563897/… 了解相关问题,其中的答案涉及使用C++11 的
constexpr:stackoverflow.com/a/24341128/368896
标签: c++ static header constants