Skip to content

Instantly share code, notes, and snippets.

@Krythz43
Created October 2, 2019 14:39
Show Gist options
  • Save Krythz43/0864b7ef7e50284151d39f6687938d7d to your computer and use it in GitHub Desktop.
Save Krythz43/0864b7ef7e50284151d39f6687938d7d to your computer and use it in GitHub Desktop.
Usage of operator overloading in structures in C++
#include <bits/stdc++.h>
using namespace std;
struct Complex {
int real, imag;
Complex(int r = 0, int i =0) {real = r; imag = i;}
Complex operator + (Complex const &obj) {
// Note that the operator on left is passed as a refrence and can be modified directly by modifying *this.
Complex res;
res.real = real + obj.real;
res.imag = imag + obj.imag;
return res;
}
void print() { cout << real << " + i" << imag << endl; }
};
int main()
{
Complex c1(10, 5), c2(2, 4);
Complex c3 = c1 + c2;
c3.print();
c1.print();
c2.print();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment