C ++ singleton small case

C ++ singleton small case

#include <iostream>
using namespace std;
class Plural
{
public:
	~Plural();
	static Plural*getPort();//获取接口
	void getXY();//打印XY
	 void setXY(int, int);
	 friend istream& operator>>(istream&, Plural*&);//重载>>
	 friend ostream& operator<<(ostream&, Plural*&);//重载<<
	 Plural& operator++();//重载前++
	 Plural& operator--();//重载前—
const Plural operator++(int);//重载后++
	 const Plural operator--(int);//重载后--
private:
	Plural();//测试单例模式	 
	int x;
	int y;
	static Plural*Port;
};
Plural*Plural::Port = NULL;//懒汉模式
Plural*Plural::Port2 = new Plural();//饿汉模式

Plural*Plural::getPort() {
	if (!Port)
	{
		Port = new Plural();
	}
	return Port;
}
Plural*Plural::getPort2() {
	return Port2;
}
Plural::Plural() {
	this->x = 0;
	this->y = 0;
}
void Plural::setXY(int x,int y)
{
	this->x = x;
	this->y = y;
}
void Plural::getXY() {
	cout << "(" << this->x << "+" << this->y << "i" << ")" << endl;
}
istream& operator>>(istream& is, Plural*& my1) //重载>>
{
	cout << "输入实部" << endl;
	is >> my1->x;
	cout << "输入虚部" << endl;
	is >> my1->y;
	return is;
}
ostream& operator<<(ostream& os, Plural*& my1) {//重载<<
	os << "(" << my1->x << "+" << my1->y << "i" << ")";
	return os;
}
Plural& Plural::operator++() {//重载前++
	++this->x;
	++this->y;
	return *this;
}
Plural& Plural::operator--() {//重载前--
	--this->x;
	--this->y;
	return*this;
}
const Plural Plural::operator++(int) {//重载后++
	
	Plural  my1 = *this;
	(this->x)++;
	(this->y)++;
	return my1;
}
const Plural Plural::operator--(int) {//重载后--
	Plural  my1 = *this;
	(this->x)--;
	(this->y)--;
	return my1;
}
Plural::~Plural()
{   //单例模式一般不需要手动释放,程序结束后会释放,如果非要手动释放,就写一个析构方法,然后默认的析构函数什么都不写
}
void main() {
	Plural* my1;
	my1 = Plural::getPort();
	//my1->setXY(1, 2);//设置XY
	
	cin >> my1;//重载>>

	++(*my1);//重载前++
	cout << my1 << endl;//重载<<
	--(*my1);//重载前--
	cout << my1 << endl;//重载<<
	(*my1)++;//重载后++
	cout << my1 << endl;//重载<<
	(*my1)--;//重载后--
	cout << my1 << endl;//重载<<
}

Renderings:
Here Insert Picture Description

Guess you like

Origin blog.csdn.net/weixin_44567289/article/details/90273870
Recommended