const member static member const static int member initialization


Regarding the initialization of const members, static members, and const static members:
1. const members: can only be initialized in the initialization list after the constructor
2. static members: initialized outside the class without static modification
3. const static members: There is only one copy of the class, and the value cannot be changed. Therefore, it can be initialized at the point of declaration in the class (const static int only), or it can be initialized outside the class like static. When initializing

outside the class, do not add the static keyword, but you need to add the const keyword


#include <iostream> 
using std::cout; 
using std::endl; 
class base 
{ 
public: 
base(int x=8):a(x){};//const成员在构造函数初始化 
const int a; 
static int b; 
const static int c=9;//const static成员在类内初始化 
}; 
int base::b=9;//static成员在类外初始化,可以修改 
//const int base::c=10;//也可以像static在类外初始化 
int main() 
{ 
base obj; 
cout<<obj.a<<endl; 
cout<<base::b<<endl; 
cout<<base::c<<endl; 
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324445926&siteId=291194637