如何在C ++中初始化静态const成员?

是否有可能在构造函数之外初始化静态常量值? 是否可以在发现成员声明的同一个地方初始化?

class A { private: static const int a = 4; /*...*/ }; 

是的,你可以,但只适用于inttypes。 如果你想要你的静态成员是任何其他types,你必须在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中被删除了(使用编译器提供的function),你可以直接在类成员声明中初始化你想要的东西。

静态数据成员(仅限C ++)

静态数据成员在类的成员列表中的声明不是一个定义。 您必须在名称空间范围内的类声明之外定义静态成员。 例如:

 class X { public: static int i; }; int X::i = 0; // definition outside class declaration 

一旦你定义了一个静态数据成员,即使没有静态数据成员的类的对象存在,它仍然存在。 在上面的例子中,即使已经定义了静态数据成员X :: i,也不存在类X的对象。

命名空间范围内的类的静态数据成员具有外部链接。 静态数据成员的初始化器在声明成员的类的范围内。

一个静态数据成员可以是任何types的,除了void或void用const或volatile限定的。 您不能将静态数据成员声明为可变的。

程序中只能有一个静态成员的定义。 未命名类,包含在未命名类和本地类中的类不能有静态数据成员。

静态数据成员及其初始化器可以访问其类的其他静态私有和受保护成员。 以下示例显示如何使用其他静态成员来初始化静态成员,即使这些成员是私有的:

 class C { static int i; static int j; static int k; static int l; static int m; static int n; static int p; static int q; static int r; static int s; static int f() { return 0; } int a; public: C() { a = 0; } }; C c; int C::i = C::f(); // initialize with static member function int C::j = C::i; // initialize with another static data member int C::k = cf(); // initialize with member function from an object int C::l = cj; // initialize with data member from an object int C::s = ca; // initialize with nonstatic data member int C::r = 1; // initialize with a constant value class Y : private C {} y; int C::m = Y::f(); int C::n = Y::r; int C::p = yr; // error int C::q = yf(); // error 

C :: p和C :: q的初始化会导致错误,因为y是从C私下导出的类的对象,并且其成员不能被C的成员访问

如果静态数据成员是const整型或常量枚举types,则可以在静态数据成员的声明中指定一个常量初始化程序。 这个常量初始值必须是一个整型常量expression式。 请注意,常量初始化器不是一个定义。 您仍然需要在封闭的命名空间中定义静态成员。 以下示例演示了这一点:

 #include <iostream> using namespace std; struct X { static const int a = 76; }; const int X::a; int main() { cout << X::a << endl; } 

静态数据成员a声明结束时的令牌= 76是一个常量初始值设定项。

为了完整起见,我添加了静态模板成员variables。

 template<class T> struct X{ static T x; }; template<class T> T X<T>::x = T(); int main(){ X<int> x; } 

你不能在构造函数中初始化静态成员。 整数types可以在声明中内联初始化。 其他静态成员必须定义(在.cpp )文件中:

 // .h class A{ private: static const int a = 4; static const foo bar; ... ... }; // .cpp const foo A::bar = ...; 

如果我记得正确的话,你不能在课堂上定义它。 你明确地需要在pablo中提到的外部定义。