【Linux基础】运算符重载为类的友元函数

来源:互联网 发布:网络大电影时空特战队 编辑:程序博客网 时间:2024/06/05 14:22
类中的声明:
friend 函数类型 operator 运算符(参数表);
运算符重载函数的定义形式:
函数类型 operator 运算符(参数表)
{
函数体;
}
例5 用友元函数实现复数类加减运算符的重载
#include "iostream.h"
class CComplex
{
private:
double real;
double imag;
public:
CComplex(double r=0, double i=0);
void Print();
friend CComplex operator +(CComplex c1,CComplex c2);
friend CComplex operator -(CComplex c1,CComplex c2);
};
CComplex::CComplex (double r, double i)
{
real = r;
imag = i;
}
void CComplex:rint()
{
cout << "(" << real << "," << imag << ")" << endl;
}
CComplex operator +(CComplex c1, CComplex c2)
{
CComplex temp;
temp.real = c1.real + c2.real;
temp.imag = c1.imag + c2.imag;
return temp;
}
CComplex operator -(CComplex c1, CComplex c2)
{
CComplex temp;
temp.real = c1.real - c2.real;
temp.imag = c1.imag - c2.imag;
return temp;
}
void main(void)
{
CComplex a(1, 2), b(3.0, 4.0), c, d, e;
c = a+b;
相当于函数调用“c=operator+(a, b)”
d = b-10;
e = 20+a;
cout << "c = ";
c.Print();
cout << "d = ";
d.Print();
cout << "e = ";
e.Print();
}
程序运行结果为:
c = (4, 6)
d = (-7, 4)
e = (21, 2)

本文转载于唯C教育,【Linux基础】运算符重载为类的友元函数
http://www.weicedu.com/forum.php?mod=viewthread&tid=78&fromuid=4
(出处: http://www.weicedu.com/)
原创粉丝点击