xxxxxxxxxx
istream& operator>> (istream& is, Date& dt)
{
is>> dt.mo>> dt.da>> dt.yr;
return is;
}
xxxxxxxxxx
#include <iostream>
class foo{
public:
foo(){} //Empty constructor
foo(int a, int b){ //Constructor takes 2 args to set the value of a and b.
this->a = a;
this->b = b;
}
int a;
int b;
/*
A function that returns a foo class when a "+" operator is applied to
2 objects of type foo.
*/
foo operator+(foo secondValue){
foo returnValue; //Temporary class to return.
returnValue.a = this->a + secondValue.a;
returnValue.b = this->b + secondValue.b;
return returnValue;
};
int main(){
foo firstValue(1,3);
foo secondValue(1,5);
foo sum;
sum = firstValue + secondValue;
std::cout << sum.a << " " << sum.b << "\n";
return 0;
}
xxxxxxxxxx
// operator overloading in c++ **sudipnext**
#include <iostream>
using namespace std;
class complex
{
int real, img;
public:
complex()
{
real = 0;
img = 0;
}
void getData()
{
cout << "Enter the real part :- " << endl;
cin >> real;
cout << "Enter the img part:- " << endl;
cin >> img;
}
complex operator+(complex &x)
{
complex temp;
temp.real = x.real + real;
temp.img = x.img + img;
return temp;
}
void display()
{
cout << "The ans are :- " << real << " " << img << endl;
}
};
int main()
{
complex obj1, obj2, obj3;
obj1.getData();
obj2.getData();
obj3 = obj1 + obj2;
obj3.display();
return 0;
}
xxxxxxxxxx
class className {
..
public
returnType operator symbol (arguments) {
..
}
..
};
xxxxxxxxxx
class X
{
public:
// friends defined inside class body are inline and are hidden from non-ADL lookup
friend X operator+(X lhs, // passing lhs by value helps optimize chained a+b+c
const X& rhs) // otherwise, both parameters may be const references
{
lhs += rhs; // reuse compound assignment
return lhs; // return the result by value (uses move constructor)
}
};
xxxxxxxxxx
// Use operator overloading to change the behaviour of division to multiplication for user defined data types
#include <bits/stdc++.h>
using namespace std;
class parent
{
int x;
public:
parent(int y)
{
this->x = y;
}
void operator/(parent p)
{
int temp = this->x * p.x;
cout << temp;
}
};
int main()
{
parent obj1(10), obj2(20);
obj2 / obj1;
return 0;
}
xxxxxxxxxx
//adding two fraction classes together
//Fraction class has a numerator, denominator field with accessors
//A new fraction class is returned with the new numerator and denominator
Fraction operator+(const Fraction& left, const Fraction& right){
int newDenom = left.denominator() * right.denominator();
int newNumerator = (left.denominator() * right.numerator()) + (right.denominator() * left.numerator());
Fraction newFraction(newNumerator, newDenom);
return newFraction;
};
xxxxxxxxxx
inline bool operator==(const X& lhs, const X& rhs){ /* do actual comparison */ }
inline bool operator!=(const X& lhs, const X& rhs){ return !(lhs == rhs); }