C++设计模式之三 单例模式

来源:互联网 发布:卡乐购卡盟源码 编辑:程序博客网 时间:2024/06/10 01:19

《Singleton.h》

#include<iostream>

#include<string>
using namespace std;


class A{
public:
    static A* GetInstance();
    void ShowAddress();


private:
A();
virtual ~A();
static A* m_p;

};


《Singleton.cpp》

#include "Singleton.h"


A*A::m_p = NULL;


A::A()
{
    cout <<"Construct Fun"<<endl;
}


A::~A()
{
delete m_p;
    cout <<"Deconstruct Fun"<<endl;
}


A* A::GetInstance()
{
    if ( m_p == NULL )
{
        m_p = new A();
    }
    return m_p;
}


void A::ShowAddress()
{
cout <<"SHOW AS"<<endl;
}


int main()
{
A::GetInstance()->ShowAddress();
return 0;
}


总结特点:

1、单例模式要求只能声明一个对象实例,为了保证则将构造函数声明为私有。

2、声明一个私有成员static对象实例指针,并在定义时初始化。

3、声明一个public的static成员函数,作用来获取该实例,在该函数定义时候,需要时创建实例。


调试时候遇到的问题:

在定义实例获取函数时候,我将该函数写成

static A* A::GetInstance()
{
    if ( m_p == NULL )
{
        m_p = new A();
    }
    return m_p;
}

加了一个“static”结果导致链接时候出错,提示“static' should not be used on member functions defined at file scope”,后来查资料才明白,此处不能加static。

总结原因如下:

问题原因:static 不能在文件区域内定义!也就是说不能在类里面定义,必须先在类里面声明然后在类外定义!

简单的说,static是针对于类的,而不是对象的,所有的对象都使用该static,原在类中声明的static成员函数,如果在定义时,加上static修饰符的话,每个对象都来操作属于所有对象(类)的东西,岂不是会乱套,所以不能允许这种行为。同理,针对于static变量一样,定义时不能加static。

下面来自于网友针对于该问题的分析,我感觉很有道理,贴过来学习一下:

错误提示:pure specifier can only be specified for functions

问题原因:不能在类里边赋static数据成员的初值

错误提示:'static' should not be used on member functions defined at file scope

问题原因:static 不能在文件区域内定义!也就是说不能在类里面定义,必须先在类里面声明然后在类外定义!

 

总结(转载如下)

1.         静态数据成员static data member 是 类的,而不是仅属于某个对象的,该类的所有对象都可以调用它,类也可以调用。对象可调用它,但不是独占。生存期:编译时就分配,程序结束才释放空间。他只能在类体外初始化。作用域:与定义它的类的作用域相同,即与类同在。他的存在是为了对象间的共同交流。

2.         静态成员函数Static member function 是为了调用static data member 而存在。Compile 不为他分配this 指针,所以他不能调用对象 的非static data member。当你非要调用 非Static data member 时,只要 指明对象就行了(因为没有compile 没有为类的static member function 指定 this 指针,所以引用 非静态成员变量时分不清是哪个对象的,当你指明对象来调用不就行了。)

 

加了static 限制符的data member or member function 只是限制了调用的权利,并没有限制 被调用的权利。非static 的对象和非static的member function 都可以调用他们。

原创粉丝点击