C++:运算符重载(详)

#include <iostream>
#include <string>
using namespace std;
class Num
{
	friend ostream& operator<<(ostream&, Num&);
	friend istream& operator>>(istream&, Num&);
public:
	Num(){}
	Num(int a ,int b):m_Numb(new int(0)),m_Numa(0)
	{ 
		m_Numa = a;
		m_Numb = new int(b);
	}
	~Num()
	{
		if (m_Numb != NULL)
		{
			delete m_Numb;
			m_Numb = NULL;
		}
	}


	//重载+
	Num operator+(Num &n)
	{
		Num x;
		x.m_Numa = this->m_Numa + n.m_Numa;
		return x;
	}
	//重载-
	Num operator-(Num &n)
	{
		Num x;
		x.m_Numa = this->m_Numa - n.m_Numa;
		return x;
	}

	//前置递增递减
	Num & operator++()
	{
		++this->m_Numa;

		return *this;
	}
	Num & operator--()
	{
		--this->m_Numa;

		return *this;
	}
	//后置递增递减
	Num operator++(int)
	{
		Num temp = *this;
		++m_Numa;
		return temp;
	}
	Num operator--(int)
	{
		Num temp = *this;
		--m_Numa;
		return temp;
	}
	//赋值运算符
	Num & operator=(Num & p)
	{
		//判断是否为空
		if (m_Numb != NULL)
		{
			delete m_Numb;
			m_Numb = NULL;
		}
		//进行深拷贝操作
		m_Numb = new int(*p.m_Numb);
		return *this;
	}
	int *m_Numb;
	//关系运算符
	bool operator == (Num & p)
	{
		if (this->m_Numa == p.m_Numa && *this->m_Numb == *p.m_Numb)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	//括号运算符
	void operator()(string x)
	{
		cout << x << endl;
	}

private:
	int m_Numa;

};
//重载输入输出流运算符
ostream& operator<<(ostream &out, Num &s)
{
	out << "m_Numa=" << s.m_Numa << endl;
	return out;
}
istream& operator>>(istream &in, Num &s)
{
	in >> s.m_Numa;
	return in;
}

//输入输出以及加减重载测试
void test1()
{
	Num n1, n2;
	cout << "请输入对象值:";
	cin >> n1 >> n2;
	Num n3 = n1 + n2;
	cout << n3;
	Num n4 = n1 - n2;
	cout << n4;;
}
//递增递减重载测试
void test2()
{
	Num n;
	cin >> n;
	cout << ++n;
	n--;
	cout << n;
	

}
//赋值运算符重载测试
void test3()
{
	Num n1(0,10);
	Num n2(0,20);
	Num n3(0,30);
	n1 = n2 = n3;
	cout << *n1.m_Numb << endl;
	cout << *n2.m_Numb << endl;
	cout << *n3.m_Numb << endl;

}
//关系运算符重载测试
void test4()
{
	Num n1(10,10),n2(10,10);
	if (n1 == n2)
	{
		cout << "相等" << endl;
	}
	else
	{
		cout << "不等" << endl;
	}
}
//括号运算符重载测试
void test5()
{
	Num n;
	n("Hello word!");
}

int main()
{


	system("pause");
	return 0;
}

test1

在这里插入图片描述

test2

在这里插入图片描述

test3

在这里插入图片描述

test4

在这里插入图片描述

test5

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值