首页 > 开发 > C++ > 正文

C++ 静态函数

2017-09-11 21:35:25  来源: 网友分享
#include<iostream>using namespace std;#define f S::init()class S{public:    static S *init(){        S *p = new S;        return p;    }    void print1(){        cout<<"1fasdf"<<endl;    }    void print2(){        cout<<"2fasdf"<<endl;    }    void print3(){        cout<<"3fasdf"<<endl;    }};int main(){    f->print1();    f->print2();    f->print3();    return 0;}

今天笔试时这道题目要求改错,但是在windows下及linux下均运行无误,求解答。

解决方案

static S *init(){        static S *p = new S;        return p;}

这个应该是考你对singleton的理解。
将init 里 p声明为静态的就可以了。
无论init被调用多少次,
static S *p = new S;这一句,在程序的生命周期,只会被执行一次。