一、运算符重载的规则
(1)符合语言语法。
(2)不能重载对内部C++数据类型进行操作的运算符。
(3)不能创建新的运算符。
(4)不能重载下面的运算符。
.类成员选择运算符。
.*成员指针运算符。
::作用域运算符。
?:条件表达式运算符。
(5)保持原有的基本语义不变。
二、运算符重载的形式
1、成员函数重载运算符
<返回值类型> operator <运算符> (<形式参数表>);
用成员函数重载运算符需要的参数的个数总比它操作数的个数少一。
2、用友元函数重载运算符
friend <返回值类型> operator <运算符> (<形式参数表>)
用友元函数重载运算符需要的参数的个数总比它操作数的个数多一。
3、举例
成员函数
#include <iostream>
using namespace std;
class Complex
{
public:
Complex(double r = 0.0, double i = 0.0);
Complex operator+(Complex c);
Complex operator-(Complex c);
void display();
private:
double real, imag;
};
Complex::Complex(double r, double i)
{
real = r;
imag = i;
}
Complex Complex::operator+(Complex c)
{
Complex temp;
temp.real = real + c.real;
temp.imag = imag + c.imag;
return temp;
}
Complex Complex::operator-(Complex c)
{
Complex temp;
temp.real = real - c.real;
temp.imag = imag - c.imag;
return temp;
}
void Complex::display()
{
char str;
str = (imag < 0) ? ' ' : '+';
cout << real << str << imag << "i" << endl;
}
int main()
{
Complex c1(1.3, 4.3), c2(5.3, 3.4);
Complex c;
c = c1 + c2; // c = c1.operator - c2
cout << " c1 + c2 = ";
c.display(); // c1 + c2 = 6.6+7.7i
c = c1 - c2;
cout << " c1 - c2 = ";
c.display(); // c1 - c2 = -4+0.9i
return 0;
}
友元函数
#include<iostream>
using namespace std;
class Complex
{
public:
Complex(double r = 0.0, double i = 0.0);
friend Complex operator+(Complex c1, Complex c2);
friend Complex operator-(Complex c1, Complex c2);
void display();
private:
double real, imag;
};
Complex::Complex(double r, double i)
{
real = r;
imag = i;
}
Complex operator+(Complex c1, Complex c2)
{
Complex temp;
temp.real = c1.real + c2.real;
temp.imag = c1.imag + c2.imag;
return temp;
}
Complex operator-(Complex c1, Complex c2)
{
Complex temp;
temp.real = c1.real - c2.real;
temp.imag = c1.imag - c2.imag;
return temp;
}
void Complex::display()
{
char str = (imag < 0) ? ' ' : '+';
cout << real << str << imag << "i" << endl;
}
int main()
{
Complex c1(3.4, 2.5), c2(5.4, 5.4);
Complex c;
c = c1 + c2;
cout << "c1 + c2 = "; // c = operator + (c1, c2)
c.display(); // c1 + c2 = 8.8+7.9i
c = c1 - c2;
cout << "c1 - c2 = ";
c.display(); // c1 - c2 = -2 -2.9i
return 0;
}