C++运算符重载

本文探讨了C++中不可重载的符号,运算符重载的两种方式(成员函数和友元函数),并比较了两者在参数处理、封装性与效率上的特点,还特别强调了`<<`和`>>`运算符的注意事项。通过实例代码解析了前后缀自增运算符的实现技巧。
摘要由CSDN通过智能技术生成

1.首先,我们先明确什么符号是不能重载的:sizeof、::、?:、.、.*这五类是不能重载的。我们也不能定义新的运算符。

2.其次,我们要明确,我们如何重载运算符:成员函数,友元函数。

3.已知2,那么这两种方法的能力一样吗?请见4

4.友元无法重载=、()、[]、->,当然,区别不只是这些,请见5

5.成员函数由于可以走后门,所以可以将参数个数减1,身为朋友的友元函数也只是朋友而已,明算账,该是几个就是几个。同时,由于友元函数会破坏类的封装性和数据的隐蔽性,但又会提高程序的运行效率,所以要权衡利弊进行使用。

6.注意,在重载插入运算符"<<"和提取运算符">>"时,应该注意到using namespace std,否则就会出现bug。

下面的代码直接拿去运行,注意我的注释,可以减少你的很多bug。

#include<iostream>
using namespace std;
class complex {
private:
	double r;
	double i;
public:
	complex(double a = 0, double b = 0):r(a), i(b) {}//注意,此时不能再定义无参构造函数,否则会发生冲突
	complex operator+(const complex& c)//“+”是双目运算符
	{
		complex t;
		t.r = r + c.r;
		t.i = i + c.i;
		return t;
	}
	complex operator+(double d)
	{
		complex t;
		t.r = r + d;
		t.i = i;
		return t;
	}
	complex operator-(const complex& a);//注意成员函数在类外定义和友元函数的不同之处
	complex& operator=(const complex& a)
	{
		if (this != &a)
		{
			r = a.r;
			i = a.i;
		}
			return *this;
	}
	friend complex operator+(const complex& a, const complex& c)
	{
		complex t;
		t.r = c.r + a.r;
		t.i = c.i + a.i;
		return t;
	}
	friend complex operator+(double d, const complex& c);
	friend ostream& operator<<(ostream& os, const complex& c)
	{
		os << "r:" << c.r << "i:" << c.i;
		return os;
	}
	void print();
};
complex complex::operator-(const complex& a)
{
	complex t;
	t.r = r - a.r;
	t.i = i - a.i;
	return t;
}
void complex::print()
{
	std::cout << r << " " << i << std::endl;
}
complex operator+(double d, const complex& c)
{
	complex t;
	t.r = c.r + d;
	t.i = c.i;
	return t;
}
int main()
{
	complex a(3, 5), b(4, 9), c;
	c = a+10.5;//由友元函数护航,成员函数无能为力
	c.print();
	c = a;
	c.print();
	cout << a;
	return 0;
}

续:

下面要提一嘴前后缀的问题了。

对比:前缀++返回的是一个引用,因此,并没有生成临时对象的开销,性能较高;相比之下,后缀++返回的是一个临时对象。所以,在写这两种重载函数时要注意到形式问题。

complex& complex::operator++()//用成员函数定义前缀++
{
	r++;
	i++;
	return *this;
}

complex complex::operator++(int dummy)//用成员函数定义后缀++
{
	complex oldval(*this);
	r++;
	i++;
	return oldval;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

静水流深-刘申

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

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

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

打赏作者

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

抵扣说明:

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

余额充值