运算符的重载形式有两种,即重载为类的非静态成员函数和重载为非成员函数。运算符重载为类的成员函数的一般语法形式为:
返回类型 operator 运算符(形参表){
函数体
}
运算符重载为非成员函数的一般语法形式为:
返回类型 operator 运算符(形参表){
函数体
}
#include
using namespace std;
class Complex{ // 复数类定义
private:
double real; // 复数实部
double imag; // 复数虚部
public:
Complex(double r = 0.0, double i = 0.0) : real(r), imag(i){} // 构造函数
Complex operator+(const Complex &c2) const; // 运算符 + 重载成员函数
Complex operator-(const Complex &c2) const; // 运算符 - 重载成员函数
void display() const; // 输出复数
};
Complex Complex::operator+(const Complex &c2) const{ // 重载运算符函数实现
return Complex(real + c2.real, imag + c2.imag); // 创建一个临时无名对象作为返回值
}
Complex Complex::operator-(const Complex &c2) const{ // 重载运算符函数实现
return Complex(real - c2.real, imag - c2.imag); // 创建一个临时无名对象作为返回值
}
void Complex::display() const{
cout // 重载运算符函数实现
return Complex(real + c2.real, imag + c2.imag); // 创建一个临时无名对象作为返回值
}
Complex Complex::operator-(const Complex &c2) const{ // 重载运算符函数实现
return Complex(real - c2.real, imag - c2.imag); // 创建一个临时无名对象作为返回值
}
也可以改写成如下形式返回函数值:
Complex Complex::operator+(const Complex &c2) const{ // 重载运算符函数实现
Complex complex(real + c2.real, imag + c2.imag); // 创建一个临时无名对象作为返回值
return complex;
}
Complex Complex::operator-(const Complex &c2) const{ // 重载运算符函数实现
Complex complex(real - c2.real, imag - c2.imag); // 创建一个临时无名对象作为返回值
return complex;
}
以非成员函数形式重载Complex的加减法运算和“} // 构造函数
friend Complex operator+(const Complex &c1, const Complex &c2); // 运算符 + 重载成员函数
friend Complex operator-(const Complex &c1,const Complex &c2); // 运算符 - 重载成员函数
friend ostream & operator // 重载运算符函数实现
Complex complex(c1.real - c2.real, c1.imag - c2.imag); // 创建一个临时无名对象作为返回值
return complex;
}
ostream & operator
Complex *complex1 = new Complex(5, 4); // 定义复数类的对象
Complex *complex2 = new Complex(2, 10);
Complex *complex3 = new Complex();
cout |