是否可以初始化一个static const
构造函数之外的数据成员?它可以在声明数据成员的同一位置进行初始化吗?
class A {
private:
static const int a = 4;
/*...*/
};
是的,你可以,但仅限于 int 类型。
如果您希望静态成员是任何其他类型,则必须在 cpp 文件中的某个位置定义它。
class A{
private:
static const int a = 4; // valid
static const std::string t ; // can't be initialized here
...
...
};
// in a cpp file where the static variable will exist
const std::string A::t = "this way it works";
另请注意,此规则已在 C++11 中删除,现在(使用提供该功能的编译器)您可以直接在类成员声明中初始化您想要的内容。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)