struct USCurrency
{
int dollars;
int cents;
};
USCurrency a = {2, 50};
USCurrency b = {1, 75};
USCurrency c = a + b; //Error
struct USCurrency
{
int dollars;
int cents;
};
USCurrency a = {2, 50};
cout << a; //Error
How to make operators work for user defined data types?
Operator Overloading
Operator overloading can be done by implementing a function which can be :
Member Function
Non-Member Function
Friend Function
Restrictions on Operator Overloading
Precedence and Associativity of an operator cannot be changed.
Arity (numbers of Operands) cannot be changed. Unary operator remains unary, binary remains binary etc.
No new operators can be created, only existing operators can be overloaded.
Cannot redefine the meaning of a procedure. You cannot change how integers are added.
#include <iostream>
using namespace std;
struct USCurrency
{
int dollars;
int cents;
};
USCurrency operator+(const USCurrency m, const USCurrency o)
{
USCurrency tmp = {0, 0};
tmp.cents = m.cents + o.cents;
tmp.dollars = m.dollars + o.dollars;
if(tmp.cents >= 100)
{
tmp.dollars += 1;
tmp.cents -= 100;
}
return tmp;
}
ostream& operator<<(ostream &output, const USCurrency &o)
{
output << "$" << o.dollars << "." << o.cents;
return output;
}
int main()
{
USCurrency a = {2, 50};
USCurrency b = {1, 75};
USCurrency c = a + b;
cout << c << endl;
return 0;
}
#include <iostream>
using namespace std;
struct USCurrency
{
int dollars;
int cents;
USCurrency operator+(const USCurrency o)
{
USCurrency tmp = {0, 0};
tmp.cents = cents + o.cents;
tmp.dollars = dollars + o.dollars;
if(tmp.cents >= 100)
{
tmp.dollars += 1;
tmp.cents -= 100;
}
return tmp;
}
ostream& operator<<(ostream &output)
{
output << "$" << dollars << "." << cents;
return output;
}
};
int main()
{
USCurrency a = {2, 50};
USCurrency b = {1, 75};
USCurrency c = a + b;
return 0;
}