Urgent Responce Required
Jun 4, 2016 at 8:02pm UTC
I was given an assignment to overload + and - operator
i want to confirm that my logic is well or not?
The program runs fine
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
#include<conio.h>
#include<iostream>
using namespace std;
class Distance
{
private :
int feet;
int inches;
public :
Distance()
{
feet=inches=0;
}
void input()
{
cout<<"*****Enter distance******" <<endl;
cout<<"Enter Feets : " <<endl;
cin>>feet;
cout<<"Enter Inches : " <<endl;
cin>>inches;
}
void show()
{
cout<<"The Distance is : " <<endl;
cout<<"Feets : " <<feet<<endl;
cout<<"Inches : " <<inches<<endl;
}
Distance operator ++()
{
Distance temp;
feet++;
inches++;
temp.feet=feet;
temp.inches=inches;
return temp;
}
Distance operator --()
{
Distance temp;
feet--;
inches--;
temp.feet=feet;
temp.inches=inches;
return temp;
}
};
int main()
{
Distance x;
x.input();
x.show();
cout<<"***** After Overloading ++ operator : " <<endl;
++x;
x.show();
cout<<"***** After Overloading -- operator : " <<endl;
--x;
x.show();
return 0;
}
Jun 4, 2016 at 9:19pm UTC
I was given an assignment to overload + and - operator
Where are your overloads for these operators? All I see is the overloads for operator++ and operator--.
i want to confirm that my logic is well or not?
I would say probably not. For those operators you probably should only increment/decrement either feet or inches, not both.
Last edited on Jun 4, 2016 at 9:21pm UTC
Jun 5, 2016 at 3:26am UTC
what difference it makes if i write + instead of ++ thats just a name
.
but i was not given any condition to increment only one of feet or inches
Jun 5, 2016 at 4:52am UTC
Because these two operators do different things. The operator+ adds two instances of your class, the operator++ only operates on one instance.
but i was not given any condition to increment only one of feet or inches
That's probably because you should be implementing operator+ not operator++.
You probably should be able to do something like the following:
1 2 3 4 5 6 7 8 9 10
Distance a;
a.input();
a.show();
Distance b;
b.input();
b.show();
Distance c = a + b;
c.show();
Jun 5, 2016 at 4:53am UTC
what difference it makes if i write + instead of ++ thats just a name
It wouldn't matter if we called it
operator, either, right?
operator+ and
operator++ do not differ in
name only . The semantics for your operators would be surprising to those familiar with the language. To be consistent with the normal behavior, they should return a reference to *this, not a copy of it.
but i was not given any condition to increment only one of feet or inches
If I increment a distance by 1 I would expect it to increase by 1, not 13. Of course, I would also expect a distance to be stored in terms of one unit, not two.
Topic archived. No new replies allowed.