C++中重载运算符
重载运算符的函数一般格式如下:
重载运算符 operator 运算符名称(形参表列)
例如,想将“+”用来Complex类(复数类)的加法计算,函数的原型可以:
Complex operator+(Complex &c1,Complex &c2);
operator是关键字,专门用来定义重载运算符的函数的。我们可以把operator+看作函数名,意思是“对运算符+重载”。
- #include "stdafx.h"
- #include <iostream>
- using namespace std;
- //复数
- class Complex
- {
- private:
- double real;
- double imag;
- public:
- Complex()
- {
- real=0;
- imag=0;
- }
- Complex(double r,double i)
- {
- real=r;
- imag=i;
- }
- Complex operator+(Complex &c2);
- void display();
- };
- //把operator+看作函数
- Complex Complex::operator+(Complex &c2)
- {
- Complex c;
- c.real=real+c2.real;
- c.imag=imag+c2.imag;
- return c;
- }
- void Complex::display()
- {
- cout<<"("<<real<<","<<imag<<"i)"<<endl;
- }
- int main(int argc, char* argv[])
- {
- Complex c1(3,4),c2(5,-10),c3;
- c3=c1+c2;
- cout<<"c1=";c1.display();
- cout<<"c2=";c2.display();
- cout<<"c3=";c3.display();
- return 0;
- }
莫愁前路无知己,天下无人不识君。