Skip to content

Instantly share code, notes, and snippets.

@frankie-yanfeng
Created March 3, 2019 09:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frankie-yanfeng/afb4e27d1c3741b53d48a081ea10567e to your computer and use it in GitHub Desktop.
Save frankie-yanfeng/afb4e27d1c3741b53d48a081ea10567e to your computer and use it in GitHub Desktop.
C++ operator Overriding (operator function)
#include <iostream>
using namespace std;
class Complex {
public:
Complex( double r = 0.0, double i= 0.0 ){
real = r;
imaginary = i;
}
double real; // real part
double imaginary; // imaginary part
};
Complex operator+ (const Complex & a, const Complex & b)
{
return Complex( a.real+b.real, a.imaginary+b.imaginary);
} // “类名(参数表)” 就代表一个对象
//Complex a(1,2), b(2,3), c;
int main() {
//std::cout << "Hello, World!" << std::endl;
Complex a(1,2), b(2,3), c,d ;
c = a+b;
cout << "real:" << c.real << " imaginary:" << c.imaginary << endl;
d=operator+(a,c);
cout << "real:" << d.real << " imaginary:" << d.imaginary << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment