C++ 宏定义实现单例模式

#define SINGLETON_DECLARATION(class_name) public: static class_name* getInstance(); public: static class_name* _instance;
#define SINALETON_DEFINITION(class_name)   \
    class_name* class_name::_instance = NULL; \
    class_name* class_name::getInstance() \
    {  \
        if(class_name::_instance == NULL)   \
        {   \
            class_name::_instance = new class_name();  \
        }  \
        return class_name::_instance; \
    }



using namespace std;

class A
{
    SINGLETON_DECLARATION(A);
public:
    char* getString() {return "A";}
};

SINALETON_DEFINITION(A);

int main()
{
    cout << A::getInstance()->getString() << endl;
    return 0;
}


你可能感兴趣的:(C/C++)