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

本文详细探讨了C++中静态变量的初始化规则,区分了const和非const静态变量的初始化方式。对于非const静态变量,无论int还是string类型,都需要在类外初始化。而对于const static变量,整型可以类内初始化,但float、double和string等类型则需要在类外初始化。同时,展示了在Visual Studio和GCC 6.3.0环境下这些规则的实际应用。
摘要由CSDN通过智能技术生成

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


IDE:visual studio
GCC:6.3.0

非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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值