1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
|
#include <iostream>
using namespace std;
class Length
{
private:
int len_inches;
public:
Length(int feet, int inches)
{
setLength(feet, inches);
}
Length(int inches){ len_inches = inches; }
int getFeet() const { return len_inches / 12; }
int getInches() const { return len_inches % 12; }
void setLength(int feet, int inches)
{
len_inches = 12 *feet + inches;
}
// Overloaded arithmetic and relational operators
friend Length operator+(Length a, Length b);
friend Length operator-(Length a, Length b);
friend bool operator<(Length a, Length b);
friend bool operator==(Length a, Length b);
};
int main()
{
Length first(0), second(0), third(0);
int ft, in;
cout << "Enter a distance in feet and inches: ";
cin >> ft >> in;
first.setLength(ft, in);
cout << "Enter another distance in feet and inches: ";
cin >> ft >> in;
second.setLength(ft, in);
//Test the + and - operators
third = first + second;
cout << "The result of adding first and second is ";
cout << third.getFeet() << " feet, ";
cout << third.getInches() << " inches.\n";
third = first - second;
cout << "The result of subtracting first minus second is ";
cout << third.getFeet() << " feet, ";
cout << third.getInches() << " inches.\n";
// Add an integer
third = 2 + second;
cout << "The result of 2 + second is ";
cout << third.getFeet() << " feet, ";
cout << third.getInches() << " inches.\n";
// Use relational operators
if (first == second)
cout << "First is equal to second.\n";
if (first < second)
cout << "First is less than second.\n";
else
cout << "First is greater than second.\n";
return 0;
}
//*************************************
// Overloaded operator + *
//*************************************
Length operator+(Length a, Length b)
{
return Length(a.len_inches + b.len_inches);
}
//*************************************
// Overloaded operator - *
//*************************************
Length operator-(Length a, Length b)
{
return Length(a.len_inches - b.len_inches);
}
//************************************
// Overloaded operator == *
//************************************
bool operator==(Length a, Length b)
{
return a.len_inches == b.len_inches;
}
//************************************
// Overloaded operator < *
//************************************
bool operator<(Length a, Length b)
{
return a.len_inches < b.len_inches;
}
|