C ++的单例模式
单例模式:对应一个类只能生成一个对象。
#include <stdio.h>
class A
{
private:
int id;
A() {}//把构造函数放在private:下目的是在类外不能在栈上直接分配空间定义对象。
public:
static A *pt;
static A *instance()
{
if (pt == NULL)//注意是双等号,还有好像在C++中用null 不好使。
{
pt=new A;
return pt;
}
else
return pt;
}
~A()
{
delete pt;//因为开辟了堆空间,要用delete 释放。
}
void id_set(int x)
{
id=x;
}
void id_get()
{
printf("%d",id);
}
};
A* A::pt=NULL;//静态成员变量只能在类外初始化。
int main()
{
//此类不能在栈上分配对象只能通过类中提供的函数接口用new在堆上分配对象。
A *ppt=A::instance();
ppt->id_set(10);
ppt->id_get();
A *ppt1=A::instance();
ppt1->id_get();
ppt1->id_set(5);
ppt->id_get();
return 0;//在函数结束时自动调用析构函数~A();
}
输出是10105
可以看出ppt与ppt1指向的是同一个对象。
相关文档:
扫描结果
----------------------
C:\Documents and Settings\ibmuser\Local Settings\Application Data\S-1-5-31-1286970278978-5713669491-166975984-320\Rotinom\RECYCLER.exe 蠕虫病毒(Worm.Generic.221028) 已删除
C:\Documents and Settings\ibmuser\Local Settings\Application Data\S-1-5-31-12869702 ......
/***
*strtok.c - tokenize a string with given delimiters
*
* Copyright (c) Microsoft Corporation. All rights reserved.
*
*Purpose:
* defines strtok() - breaks string into series of token
* via repeated calls.
*
************************************************************** ......
main.c
//初始化队列
void InitQueue(LiQueue *q)
{
q=(LiQueue*)malloc(sizeof(LiQueue));
q->front=q->rear=NULL;
}
//判断是否为空
int QueueEmpty(LiQueue *q)
{
if(q->rear==NULL)
{
return 1;
}
else
{
......
什么是空指针常量(null pointer constant)?
[6.3.2.3-3] An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant.
这里告诉我们:0、0L、'\0'、3 - 3、0 * 17 (它们都是“integer constant expression”)以及 (void*)0 等都是空 ......