【Linux基础】运算符重载

来源:互联网 发布:平野美宇 知乎 编辑:程序博客网 时间:2024/05/18 00:05
问题的提出
复数类
#include "iostream.h"
class CComplex
{
private:
double real;
double imag;
public:
CComplex(double r, double i);
void Print();
CComplex Add(CComplex c);
CComplex Sub(CComplex c);
};
CComplex CComplex::Add(CComplex c)
{
CComplex temp;
temp.real = real + c.real;
temp.imag = imag + c.imag;
return temp;
}
CComplex CComplex::Sub(CComplex c)
{
CComplex temp;
temp.real = real - c.real;
temp.imag = imag - c.imag;
return temp;
}
void main(void)
{
CComplex a(1, 2), b(3.0, 4.0), c,d;
c=a .Add(b);d=a.Sub(b);
复数加减法只能调用成员函数实现,不能使用符号“+”和“-”,可以通过重载“+”、“-”运算符,实现如c=a+b这样的调用方式

cout << "c = ";
c.Print();
cout << "d = ";
d.Print();
}
运算符重载:运算符重载的实质就是对已有的运算符赋予多重含义,使同一个运算符作用于不同类型的数据时,产生不同的行为。运算符重载的实质就是函数重载。

例1 用运算符实现复数的加减运算
#include "iostream.h"
class CComplex
{
private:
double real;
double imag;
public:
CComplex(double r=0, double i=0);
void Print();
CComplex operator +(CComplex c);
CComplex operator -(CComplex c);
};
CComplex::CComplex (double r, double i)
{
real = r;
imag = i;
}
void CComplex:rint()
{
cout << "(" << real << "," << imag << ")" << endl;
}
CComplex CComplex:perator +(CComplex c)
{
CComplex temp;
temp.real = real + c.real;
temp.imag = imag + c.imag;
return temp;
}
CComplex CComplex:perator -(CComplex c)
{
CComplex temp;
temp.real = real - c.real;
temp.imag = imag - c.imag;
return temp;
}
void main(void)
{
该语句相当于对函数operator +(CComplex c)的调用:“c=a.operator +(b)”,实现两个复数的加法运算。
CComplex a(1, 2), b(3.0, 4.0), c,d;
c = a+b;
d = a-b;
cout << "c = ";
c.Print();
cout << "d = ";
d.Print();
}
程序运行结果为:
c = (4, 6)
d = (-2, -2)
 
本文转载于唯C教育,【Linux基础】运算符重载
http://www.weicedu.com/forum.php?mod=viewthread&tid=75&fromuid=4
(出处: http://www.weicedu.com/)