C++:定义一个复数类,重载+-运算符,同时重载两个版本的<<运算符

首先重载加减运算符

class plural 
{
public:
	plural(float real = 0.0, float vir = 0.0) :real(real), vir(vir) { cout << "有参构造" << endl; }
	plural(const plural& p) :real(p.real), vir(p.vir) { cout << "拷贝构造" << endl; }

	plural operator+(const plural& p) const 
	{
		return plural(real + p.real, vir + p.vir);
	}

	plural operator-(const plural& p) const 
	{
		return plural(real - p.real, vir - p.vir);
	}

private:
	float real; // 实部
	float vir; // 虚部
};

      

        重载分为两种:

(1)重载为类成员函数,这种情况下重载函数的第一个参数是隐式的this指针,就比如上面的operator+,参数是两个plural类对象,但是只需要传一个参数。此时我们调用时可以有一下两种写法,因为函数返回一个临时对象,我们用p3和p4去接收

int main()
{
	plural p1(10,20);
	cout << p1 << endl;

	plural p2(10);
	cout << p2 << endl;
	
	plural p3(p1.operator+ (p2));
	cout << p3 << endl;

	plural p4 = p1 - p2;
	cout << p4 << endl;
}

第一种写法就是传统的调用函数并传参的写法:plural p3(p1.operator+ (p2));

第二种就是重载后的简单写法:plural p4 = p1 - p2;

如果想要直接通过cout输出plural类对象,我们还得重载<<运算符,如果我们重载为类成员函数,那么代码如下:

	ostream& operator<<(ostream& os) 
	{
		if (this->vir == 0) 
		{
			os << this->real;
		}
		else 
		{
			os << this->real << "+" << this->vir << "i";
		}
		return os;
	}

这个函数有两个参数,第一个是隐式的this指针,第二个是输出流对象os,插入运算符(operator<<)是有先后顺序的,也就是说,这样写的会导致实际运算是这样的: "类对象 << cout" , 所有我们不能像常规输出一样:
"cout << 类对象" , 我们必须显示调用重载函数,如下:

p4.operator<<(cout) << endl;

亦或是:

p4 << cout << endl;

这种形式才能打印到屏幕,这很明显不符合我们的预期,那种就只能使用另一种重载方式

(2)重载为类的友元函数

	friend ostream& operator<<(ostream& os, const plural& p) 
	{
		if (p.vir == 0) 
        {
			os << p.real;
		}
		else 
        {
			os << p.real << "+" << p.vir << "i";
		}
		return os;
	}

这两个参数的顺序依然不能调换,不然调用的时候也得调换 . 因为类成员为私有属性,这个函数需要写为类的友元函数,如果写在类外需要去掉friend,同时在类内使用friend进行友元声明,这时候就可以直接通过cout对类对象进行输出了

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

头发乌黑茂密

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值