C++類靜態成員變量和const常量在定義類的時候就必須初始化,否則都會編譯出錯。
而具初始化方法為:
C++類靜態成員變量初始化方法
#include <iostream> #include <string> #include <cstdio> #include <cstring> using namespace std; class A{ public: static void fun() { ab = 2; cout << ab << endl; } private: static int ab; }; int A::ab = 10//在此初始化 int main(int argc, char *argv[]) { A::fun(); return 0; } #include <iostream> #include <string> #include <cstdio> #include <cstring> using namespace std; class A{ public: static void fun() { ab = 2; cout << ab << endl; } private: static int ab; }; int A::ab = 10//在此初始化 int main(int argc, char *argv[]) { A::fun(); return 0; }
C++類const常量初始化方法:
#include <iostream> #include <string> #include <cstdio> #include <cstring> using namespace std; class A{ public: A:ab(10)//在此初始化ab { ;} static void fun() { ab = 2; cout << ab << endl; } const int ab; }; #include <iostream> #include <string> #include <cstdio> #include <cstring> using namespace std; class A{ public: A:ab(10)//在此初始化ab { ;} static void fun() { ab = 2; cout << ab << endl; } const int ab; };