C++类内静态变量初始化

参考博客:https://blog.csdn.net/Yang_137476932/article/details/117231323

C++类内静态变量初始化

非const static均需在类外初始化

//string
#include<iostream>
#include <string>
using namespace std;
class A
{
public:
       static string a;
};
 string A::a="666";
int main()
{
    cout<<A::a<<endl;
    system("pause");
    return 0;
}、
//int

#include<iostream>
#include <string>
using namespace std;
class A
{
public:
       static int a;
};
 int A::a=1;
int main()
{
    cout<<A::a<<endl;
    system("pause");
    return 0;
}

类内定义均报错。

const static

泛整型可以类内直接初始化,包括bool short int long等,其余类型包括float,double及string等都不可以。

#include<iostream>
#include <string>
using namespace std;
class A
{
public:
       const static bool a=1;
       const static short b=1;
       const static int c=1;
       const static long d=1;
       const static long long e=1;
       const static unsigned int f=1;
       //const static float f=1; //error
       //const static double f=1;//error
       //const static string g="a";//error
};
 //const int A::a=1;
int main()
{
    cout<<A::a<<endl;
    system("pause");
    return 0;
}

类外均可以

#include<iostream>
#include <string>
using namespace std;
class A
{
public:
       const static bool a;
       const static short b;
       const static int c;
       const static long d;
       const static long long e;
       const static unsigned int f;
       const static float g; 
       const static double h;
       const static string i;
};
const  bool  A::a=1;
const  short  A::b=1;
const  int  A::c=1;
const  long  A::d=1;
const  long long  A::e=1;
const  unsigned int  A::f=1;
const  float  A::g=1;
const  double  A::h=1;
const  string A::i="1";

 //const int A::a=1;
int main()
{
    cout<<A::a<<endl;
    system("pause");
    return 0;
}
文章目录