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;
}
__self 改为指针实现
delete Base::GetBase(); 释放空间。若没有这条语句,则析构不会被调用。
构造函数可以放在private 区域,析构不行。
posted @ 2022-02-16 11:29  Ccluck_tian  阅读(91)  评论(0编辑  收藏  举报