用static 创建类的单例

1.0 说明

通过函数调用new的static 类对象,由于static 对象只能初始化一次,由此构成单例运行。


2.0  直接代码

代码为windows,win32工程,因为只有一个文件,不上传工程了。直接贴。

// **.cpp : 定义控制台应用程序的入口点。
//

/************************************************************************/
/* 通过函数,获取某类为静态类,从而保证单例运行。
 * 通过测试,_test_single_和_test_single__2 通过函数get_single_index_class
 * 函数来获取的静态对象的指针地址相同,因为对象为静态对象。
/************************************************************************/
//#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>


class base
{
public:
	virtual bool	func() = 0;
	virtual int		get_b() = 0;
	virtual void	set_b(int){
		printf("------------------------------this is  base class set_b function;
");
	};
protected:
	base(){}
};
class Derive :public  base
{
public:
	Derive& operator= (const Derive& rhs);
	 bool func();
	 int get_b();
	 void	set_b(int b_){
		 printf("------------------------------this is  derive class set_b function;
");
		 b = b_;
	 }
	 void initial(){ b = -1;}
private:
	int b;

};
bool Derive::func()
{
	return true;
}
int Derive::get_b()
{
	return b;
}

base* get_index_class()
{	
	return   (base*)(new Derive());
}

base* get_single_index_class()
{	
	static Derive* _derive_index = new Derive();
	return   (base*)(_derive_index);
}

base* get_brand_new_single_index_class()
{	
	static Derive* _derive_index = new Derive();
	_derive_index->initial();
	return   (base*)(_derive_index);
}

int main(int argc, char* argv[])
{	
	/*-------------------------test new ---------------------------------------------*/
	base* _test = get_index_class();
	_test->set_b(12);
	int b = _test->get_b();
	printf("input data is : %d,
",b);
	//
	base* _test_2 = get_index_class();
	int b_2 = _test_2->get_b();
	printf("get_b is : %d,
",b_2);

	/*-------------------------test single new -----------------------------------------*/
	base* _test_single_ = get_single_index_class();
	_test_single_->set_b(13);
	int b_single = _test_single_->get_b();
	printf("single class input data is : %d,
",b_single);
	//
	base* _test_single__2 = get_single_index_class();
	int b_single_2 = _test_single__2->get_b();
	printf("single get_b is : %d,
",b_single_2);

	/*-------------------------test single brand-new -----------------------------------------*/
	base* _test_brand_new_single_ = get_brand_new_single_index_class();
	_test_brand_new_single_->set_b(13);
	int b_brand_new_single = _test_brand_new_single_->get_b();
	printf("brand_new single class input data is : %d,
",b_brand_new_single);
	//
	base* _test_brand_new_single__2 = get_brand_new_single_index_class();
	int b_brand_new_single_2 = _test_brand_new_single__2->get_b();
	printf("brand_new single get_b is : %d,
",b_brand_new_single_2);

		
	system("Pause");
	return 0;
}

3.0 结果



自己留着用。

不足之处,多多指教。非常感谢!



原文地址:https://www.cnblogs.com/qitian1/p/6461987.html