Skip to content

Instantly share code, notes, and snippets.

@shivajichalise
Last active July 28, 2021 02:51
Show Gist options
  • Save shivajichalise/22c736dcc3bd57055ba8d85711019dec to your computer and use it in GitHub Desktop.
Save shivajichalise/22c736dcc3bd57055ba8d85711019dec to your computer and use it in GitHub Desktop.
Operator Overloading in C++
#include <iostream>
using namespace std;
class Complex{
private:
int real, imag;
public:
Complex(){
real = 0;
imag = 0;
}
Complex(int r, int i){
real = r;
imag = i;
}
void print(){
cout << "Complex number is: " << real << " + " << imag << "i" << endl;
}
Complex operator +(Complex c){
Complex temp;
temp.real = real+c.real;
temp.imag = imag+c.imag;
return temp;
}
};
int main()
{
Complex c(1,2);
Complex c1(2,5);
Complex c2;
c.print();
c2 = c+c1;
c2.print();
return 0;
}
#include <iostream>
#include <string.h>
using namespace std;
class String{
private:
char str[4];
public:
void getString(){
cout << "Enter the string: "; cin >> str;
}
void print(){
cout << "String is: " << str << endl;
}
String operator +(String s){
String temp;
strcpy(temp.str, str);
strcat(temp.str, s.str);
return temp;
}
};
int main(){
String s, s1, s2;
s.getString();
s1.getString();
s2 = s + s1;
s2.print();
return 0;
}
#include <iostream>
using namespace std;
class Counter{
private:
int count;
public:
Counter(){
count = 0;
}
void print(){
cout << "Count: " << count << endl;
}
Counter operator ++(){
Counter temp;
temp.count = ++count;
return temp;
}
Counter operator ++(int){
Counter temp;
temp.count = count++;
return temp;
}
};
int main(){
Counter c;
Counter c1;
// ++c;
// c++;
// c.print();
c1 = ++c;
//c1 = c++;
c1.print();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment