static对象是单例的,只有一份内存,还可以用来实现单一对象

直接上代码

#include<iostream>
#include<vector>
#include<math.h>
#include<algorithm>
#include<string.h>
using namespace std;

class A{
public:
    static A& get_only_object();
    void setup();
private:
    A();
    A(const A&);
    //static A a;

};
A& A::get_only_object(){
    static A a;//该对象只有一份
    return a;
}

int main(int argc, char const *argv[])//测试
{  
    A::get_only_object();//只能直接用这个对象
    //A a=A::get_only_object();不能用一个该对象来接受这个函数的返回值
    //只是产生一个对象
    system("pause");
    return 0;
}




posted @ 2023-02-24 12:39  铜锣湾陈昊男  阅读(8)  评论(0)    收藏  举报