C++ 若在两个cpp中定义类名相同,但定义不同的单例模式,分别获取实例,是一个实例吗?

//test.cpp
void fun1();
void fun2();
int main()
{
	fun1();
	fun2();
}
//single1.cpp
#include <iostream>
using namespace std;

class single
{
private:
	string name;
	~single()
	{
		cout << "single1 go" << endl;
	}
	single()
	{
		name = "single1";
	}
	friend ostream& operator<<(ostream& os, single& ptr)
	{
		return cout << ptr.name << endl;
	}
public:
	single(single const&) = delete;
	void operator=(single const&) = delete;
	static single& get_instance()
	{
		static single thissingle;
		return thissingle;
	}
};
void fun1()
{
	cout << &single::get_instance() << endl;
}

//single.cpp
#include <iostream>
using namespace std;

class single
{
private:
	string name;
	~single()
	{
		cout << "single2 go" << endl;
	}
	single()
	{
		name = "single2";
	}
	friend ostream& operator<<(ostream& os, single& ptr)
	{
		return cout << ptr.name << endl;
	}

public:
	void funnnn()
	{
		cout << "add fun" << endl;
	}
	single(single const&) = delete;
	void operator=(single const&) = delete;
	static single& get_instance()
	{
		static single thissingle;
		return thissingle;
	}
};
void fun2()
{
	cout << &single::get_instance() << endl;
	single::get_instance().funnnn();
}

输出:
00007FF6B5F65640
00007FF6B5F65640
add fun
single1 go

结论:

  1. 是生成的同一个类,但是是根据single1.cpp中的定义来实现的。
  2. 无论我是先调用fun1()还是fun2(),生成的都是single1.cpp中定义的实例。
  3. 有趣的是,如果在single2中调用funnnn(),那么也能成功调用!所以这个实例到底是什么性质,依据什么来初始化?我的知识量还不能找到答案。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值