运算符重载

1.运算符

    C++预定义表示对数据的运算,如+,-,*,/,%,^,&,~,|,!,=,<<,>>,!=等等。只能用于基本的数据类型(整形、实型、字符型、逻辑型等)

2.自定义数据类型与运算符重载

    C++提供了数据抽象的手段:用户自己定义数据类型(类)而类的成员函数-》操作对象很不方便
    运算符重载:对抽象数据类型也能够直接使用C++提供的运算符:程序更简洁,代码更容易理解
                            对已有的运算符赋予多重的含义;使同一运算符作用于不同数据类型时-》不同类型的行为
     目的:扩展C++中提供的运算符的适用范围,以用于类所表示的抽象类型
eg.
(5,10i)+(4,8i)=(9,18i);
5+4=9;

3.运算符重载

运算符重载的实质是函数重载
返回值类型   operator运算符 (形参表)
{
……
}
 

4.运算符重载为普通函数

#include <iostream>
#include <string>
using namespace std;
class Complex {
public:
	Complex(double r = 0.0, double i = 0.0) {  //构造函数
		real = r;     //初始化实部虚部
		imaginary = i;
	}
	double real;   //定义两个成员变量
	double imaginary;
};
Complex operator+(const Complex &a, const Complex &b) //重载函数
{
	return Complex(a.real+b.real,a.imaginary+b.imaginary);
}//类名(参数表)就代表一个对象

void main()
{
	Complex a(1, 2), b(2, 3), c;
	c = a + b;//相当于 operator+(a,b)
	cout << "When a(1,2)+b(2,3)" << endl;
	cout << "The real is:"<<c.real<<"\nThe imaginary is:"<<c.imaginary << endl;
}

5.运算符重载为成员函数

#include <iostream>
#include <string>
using namespace std;
class Complex {
public:
	Complex(double r = 0.0, double m = 0.0):
		real(r),imaginary(m){}   //constructor
	Complex operator+ (const Complex &); //addition
	Complex operator- (const Complex &); //subtraction
//private:
	double real;   //定义两个成员变量
	double imaginary;
};

//Overloaded addition operator
Complex Complex::operator+(const Complex & operand2)
{
	return Complex(real+operand2.real,imaginary+operand2.imaginary);
}

//Overloaded subtraction operator
Complex Complex::operator-(const Complex & operand2)
{
	return Complex(real-operand2.real,imaginary-operand2.imaginary);
}
int main()
{
	Complex a(1.5, 2.8), b(2.3, 3.7), c,d;
	c = a + b;// x=y.operator+(z)
	d = a - b;// x=y.operator-(z)
	cout << c.real << "\t" << c.imaginary << endl;
	cout << d.real << "\t" << d.imaginary << endl;
	return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值