use*_*496 14 c++ static const header
我有一个类,我想std::string通过getter 存储一个真正的const或有效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我想在头文件而不是源文件中使用声明的原因.这是一个将被扩展的类,它的所有其他函数都是纯虚拟的,所以我目前除了这些变量之外没有其他原因要有源文件.
那么怎么做呢?
小智 16
一种方法是定义一个在其中具有静态变量的方法.
例如:
class YourClass
{
public:
// Other stuff...
const std::string& GetString()
{
// Initialize the static variable
static std::string foo("bar");
return foo;
}
// Other stuff...
};
Run Code Online (Sandbox Code Playgroud)
这只会初始化静态字符串一次,每次调用该函数都会返回对该变量的常量引用.对你有用.
Yu *_*Hao 13
您只能在构造函数中为整数类型而不是其他类型初始化静态const值.
将声明放在标题中:
const static std::string foo;
Run Code Online (Sandbox Code Playgroud)
并将定义放在.cpp文件中.
const std::string classname::foo = "bar";
Run Code Online (Sandbox Code Playgroud)
如果初始化在头文件中,那么包含头文件的每个文件都将具有静态成员的定义.将会出现链接器错误,因为初始化变量的代码将在多个.cpp文件中定义.
| 归档时间: |
|
| 查看次数: |
34997 次 |
| 最近记录: |