c++ static成员变量 {} 语法
目录
代码 1.0
#include <iostream>
class Base{
private:
static Base __self;
int id = 0;
public:
Base(){
std::cout << "Base init" << std::endl;
}
~Base(){
std::cout << "Base destory" << std::endl;
}
void printId(){
std::cout << " Id : " << id << std::endl;
}
static Base* GetBase(){
return &__self;
}
};
Base Base::__self{}; //不能用小括号方式初始化 Base Base::__self();
int main(){
std::cout << "main init" << std::endl;
Base::GetBase()->printId();
return 0;
}
运行结果
Base init
main init
Id : 0
Base destory
若没有Base Base::__self{};
,静态成员变量未初始化, 链接时报错:
/tmp/cc0f7QmX.o: In function `Base::GetBase()':
main.cpp:(.text._ZN4Base7GetBaseEv[_ZN4Base7GetBaseEv]+0x7): undefined reference to `Base::__self'
collect2: error: ld returned 1 exit status
若将Base Base::__self{};
改成 Base Base::__self();
则报错:
main.cpp:22:19: error: no ‘Base Base::__self()’ member function declared in class ‘Base’
Base Base::__self();
^
若把析构和构造都放在private区域,行为正常。
代码2.0
#include <iostream>
class Base{
private:
static Base* __self;
//static Base __self;
int id = 0;
Base(){
std::cout << "Base init" << std::endl;
}
public:
~Base(){
std::cout << "Base destory" << std::endl;
}
void printId(){
std::cout << " Id : " << id << std::endl;
}
static Base* GetBase(){
return __self;
//return &__self;
}
};
Base* Base::__self = new Base();
//Base Base::__self;
int main(){
std::cout << "main init" << std::endl;
Base::GetBase()->printId();
delete Base::GetBase(); //需要释放对象
return 0;
}