运算符重载
运算符重载指赋予运算符新的操作功能,主要用于对类的对象的操作
- 运算符
+意味着多少对象类型的加法呢? - 还可以定义新的对象类型加法
操作符重载,就是把已经定义的、有一定功能的操作符进行重新定义,来完成更为细致具体的运算等功能。
运算符重载定义形式
这里有关键字operator
<类型> <类名>::operator <操作符>(<参数表>)
{
函数体
}
运算符重载举例(两个虚数的运算符重载)
- 首先定义虚数类
- 虚数可以描述为:
a+bi - a与b看成实数,定义成double类型
- 虚数可以描述为:
- 成员函数除了构造与析构外,还有:
- 输出虚数、修改虚数、得到实部a、得到虚部b
- 相加
+、判相等== - 单目运算符(
++i,i++)等
虚函数的定义
#include <iostream>
using namespace std;
class Complex
{
private:
double real, imag;
public:
Complex(double r=0, double i=0): real(r), imag(i){ } // 构造函数
double Real(){return real;}
double Imag(){return imag;}
Complex operator +(Complex&); // 这里参数只有一个是直接与自己内部成员变量进行操作
Complex operator +(double);
bool operator ==(Complex);
Complex operator ++(); // 前置运算符 ++i
Complex operator ++(int); // 后置运算符 i++ 用int参数来区分
~Complex(){ };
}
类外定义成员函数
Complex Complex::operator + (Complex &c) // 重载运算符 +,两边是虚数对象
{
Complex temp;
temp.real = real + c.real;
temp.imag = imag + c.imag;
return temp;
}
Complex Complex::operator + (double d) // 重载运算符+,左边是虚数对象,右边是双精度数
{
Complex temp;
temp.real = real+d; // 只进行实部的相加
temp.imag=imag;
return temp;
}
bool Complex::operator ==(Complex c) // 重载运算符==
{
if (real == c.real && imag == c.imag)
return true;
else
return false;
}
Complex Complex::operator ++()
{
real += 1;
return *this;
}
Complex Complex:: operator ++(int)
{
real += 1;
return *this;
}
测试主函数
int main()
{
Complex c1(3,4), c2(5,6), c3;
cout << "C1 = " << c1.Real() << "+j" << c1.Imag() << endl;
cout << "C2 = " << c2.Real() << "+j" << c2.Imag() << endl;
c3 = c1 + c2;
cout << "C3 = " << c3.Real() << "+j" << c3.Imag() << endl;
c3 = c3+6.5;
cout << "C3 + 6.5 = " << c3.Real() << "+j" << c3.Imag() << endl;
if ( c1 == c2 )
cout<<"两个复数相等";
else
cout<<"两个复数不相等";
++c1;
cout << "++C1 = " << c1.Real() << "+j" << c1.Imag() << endl;
c2++;
cout << "++C2 = " << c2.Real() << "+j" << c2.Imag() << endl;
return 0;
}

总结
- 运算符重载是多态的另一种表现形式,许多基本运算符都可以实现重载
- 运算符重载的作用是免去了调用的麻烦
本文详细介绍了运算符重载的概念及其实现方式,并通过虚数类的实例展示了如何重载加法、比较等于等运算符,使用户可以更加直观地理解这一特性。
4129

被折叠的 条评论
为什么被折叠?



