为类myComplex重载运算符“+”“-”(P152)
/*
重载运算符的概念:
C++中的表达式由运算符和操作数按照规则构成。C++中提供了运算符重载机制,将算术运算符用于像复数这样的对象,解决对象之间的运算问题。
a.成员访问运算符 .
b.成员指针访问运算符 .*, ->*
c.域运算符 ::
d.长度运算符 sizeof
e.条件运算符 ?:
f.预处理符号 #
两个运算符,系统提供了默认的重载版本。
赋值运算符=和地址运算符&。
对于=,系统默认重载为对象成员变量的复制。
对于&,系统默认重载为返回任何类对象的地址。
运算符重载的实质是编写以运算符为名称的函数,使用运算符的表达式就被解释为对重载函数的调用。函数名由关键字operator和其后要重载的运算符符号构成。
返回值类型 operator 运算符(形参表)
{
函数体
}
1、如果定义为全局函数,对于二元运算符,需要为函数传递两个参数,即函数的参数个数就是运算符的操作个数,运算符的操作数就成为函数的实参。
2、如果定义为类的成员函数,对于二目运算符,则只需要传递一个参数,即函数的参数个数就是运算符的操作数个数减1.
*/
#include <iostream>
using namespace std;
class myComplex
{
private:
double real, imag;
public:
myComplex();
myComplex(double x, double i);
void outCom();
myComplex operator-(const myComplex &c);
friend myComplex operator+(const myComplex &c1, const myComplex &c2);//声明友元函数
};
myComplex::myComplex()
{
real = 0;
imag = 0;
}
myComplex::myComplex(double r, double i)
{
real = r;
imag = i;
}
void myComplex::outCom()
{
cout << "(" << real << "," << imag << ")";
}
myComplex myComplex::operator-(const myComplex &c)
{
return myComplex(this->real - c.real, this->imag - c.imag);
}
myComplex operator+(const myComplex &c1, const myComplex &c2)//友元函数可以直接在类外定义
{
return myComplex(c1.real + c2.real, c1.imag + c2.imag);
}
int main()
{
myComplex c1(1,2), c2(3,4),res;
c1.outCom();
cout << "operator+";
c2.outCom();
cout << "=";
res = c1 + c2;
res.outCom();
cout << endl;
c1.outCom();
cout << "operator-";
c2.outCom();
cout << "=";
res = c1 - c2;
res.outCom();
cout << endl;
system("pause");
return 1;
}

浙公网安备 33010602011771号