C++重载运算符的几类使用方法
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
1.非运算符重载实现复数的加法运算//非运算符重载实现复数的加法运算
//complex.h
#include
#ifndef COMPLEX_H
#define COMPLEX_H
class complex
{
public:
complex();
doublegetreal();
doublegetimag();
voidsetreal(double);
voidsetimag(double);
void display();
private:
double real;
double image;
};
#endif
//complex.cpp
#include
#include"complex.h"
complex::complex()
{
real = 0;
image = 0;
}
void complex::setreal(double r)
{
real = r;
}
void complex::setimag(double i)
{
image = i;
}
double complex::getreal()
{
return real;
}
double complex::getimag()
{
return image;
}
void complex::display()
{
cout<<"the result is\n"< } //test.cpp #include #include"complex.h" complex add(complex comp1,complex comp2); complex sub(complex comp1,complex comp2); void main() { complex c1,c2,c3,c4; c1.setreal(2.0); c1.setimag(3.0); c2.setreal(1.0); c2.setimag(4.0); c3 = add(c1,c2); cout<<"c3 = c1 + c2 , "; c3.display(); c4 = sub(c1,c2); cout<<"c4 = c1 - c2 ,"; c4.display(); } complex add(complex comp1,complex comp2) { complex temp; temp.setreal(comp1.getreal() + comp2.getreal()); temp.setimag(comp1.getimag() + comp2.getimag()); return temp; } complex sub(complex comp1,complex comp2) { complex temp; temp.setreal(comp1.getreal() - comp2.getreal()); temp.setimag(comp1.getimag() - comp2.getimag()); return temp; } 2.运算符重载作为类的成员函数 //运算符重载作为类的成员函数 //complex.h #include #ifndef COMPLEX_H #define COMPLEX_H class complex { public: complex(double = 0.0,double = 0.0); complex operator+ (const complex &); complex operator- (const complex &); complex& complex::operator= (const complex &); void display(); private: double real; double image; }; #endif //complex.cpp #include #include"complex.h" complex::complex(double r,doublei) { real = r; image = i; } complex complex::operator+(const complex &c2)//定义重载运算符函数{ complex c; c.real = real + c2.real; c.image = image + c2.image; return c; } complex complex::operator-(const complex &c2)//定义重载运算符函数{ complex c; c.real = real - c2.real; c.image = image - c2.image; return c; } complex& complex::operator= (const complex &right) { real = right.real; image = right.image; return *this;