读书人

单间模式求解释。解决方案

发布时间: 2012-03-17 19:06:28 作者: rapoo

单间模式,求解释。

C/C++ code
// ThinkingInCpp.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include <iostream>using namespace std;class Singleton{private:    static Singleton s;    int i;    Singleton(int x):i(x){}    void operator=(Singleton &s){s.i = this->i;};    Singleton(Singleton &s){this->i = s.i;}public:    static Singleton & getHandle()    {        return s;    }    int getValue()    {        return i;    }    void setValue(int x)    {        i = x;    }};Singleton Singleton::s(50);    //发生了什么,有没有s对象 int _tmain(int argc, _TCHAR* argv[]){        Singleton & s = Singleton::getHandle ();  //发生了什么。    cout<<s.getValue()<<endl;    system("pause");     return 0;}


构造函数什么时候调用的。

[解决办法]
Singleton Singleton::s(50); 这个是静态成员的定义

Singleton & s = Singleton::getHandle (); //引用该类的静态成员

读书人网 >C++

热点推荐