C++之运算符重载

运算符重载的实现主要就是定义重载运算符操作的函数,使得指定的运算符不仅能实现原有的功能,还能实现新定义运算符操作函数的功能。在使用被重载的运算符时,系统就自动调用该函数,以实现相应的功能。

对运算符重载的实现一般有两种处理方式

        1.把运算符重载的函数作为类的成员函数;

        2.运算符重载的函数不是类的成员函数,在类中把它声明为友元函数

重载双目运算符,如下程序:

class complex_num
{
public:
	complex_num() { imaginary = 0; real = 0; }//默认构造函数
	~complex_num() {}//析构函数
	complex_num(float real_num, float imag_num) :real(real_num), imaginary(imag_num) {}
	friend complex_num operator +(const complex_num& a, const complex_num& b);
	complex_num operator *(const complex_num& a);
private:
	float imaginary;
	float real;
};
//friend complex_num operator +(const complex_num& a, const complex_num& b);
//重载双目运算符,友元函数
complex_num operator +(const complex_num& a, const complex_num& b)
{
	complex_num	c;
	c.imaginary = a.imaginary + b.imaginary;
	c.real = a.real + b.real;
	return c;
}
//complex_num operator *(const complex_num& a);
//重载双目运算符,成员函数
complex_num complex_num::operator *(const complex_num& a)
{
	complex_num c;
	c.real = real * a.real - imaginary * a.imaginary;
	c.imaginary = real * a.imaginary + imaginary * a.real;
	return c;
}

重载单目运算符,如下程序: 

class complex_num
{
public:
	complex_num() { imaginary = 0; real = 0; }
	~complex_num() {}
	complex_num(float real_num, float imag_num) :real(real_num), imaginary(imag_num) {}
	complex_num	operator ++();
	friend complex_num operator --(complex_num& A);
private:
	float imaginary;
	float real;
};
//friend complex_num operator --(complex_num& A);
//重载单目运算符,友元函数,自减运算
complex_num operator --(complex_num& A)
{
	--A.real;
	--A.imaginary;
	return A;
}
//complex_num	operator ++();
//重载单目运算符,成员函数,自加运算
complex_num	complex_num::operator ++()
{
	++imaginary;
	++real;
	return *this;
}

重载流运算符 (一般都是用友元函数进行重载),如下程序:

class student
{
public:
	friend istream& operator>>(istream& input, student& c)
	{
		cout << "input the name and sex:" << endl;
		input >> c.name >> c.sex;
		return input;
	}
	friend ostream& operator<<(ostream& output, student& c)
	{
		output << c.name << " - " << c.sex << endl;
		return output;
	}
private:
	string name;
	string sex;
};
//主函数
int main()
{
	student stu1;
	cin >> stu1;
	cout << stu1;
	return 0;
}
input the name and sex:
suhuayong
man
suhuayong - man

运算符的重载实际上就是函数的重载。

the end~

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值