Opreator Overloading

May 31, 2016 at 1:20pm
i'm having a problem writing the code of this program !!!
can U help me???

Overload operators for the class Distance with
attributes of int feet and int inches.

Following operators must be overloaded!

+
-
/
*

+=
-=
May 31, 2016 at 2:41pm
i'm having a problem writing the code of this program

What program?

You're going to have to show us your code (using code tags please) if you want some help.
May 31, 2016 at 3:22pm
i am writing program for + operator. here's my code
guide me for the errors ThaNKS

#include <iostream>
#include<conio.h>
using namespace std;

class distance
{
private:
int inches;
int feet;
public:
distance()
{
inches=0;
feet=0;
}
distance opreator ++(distance p)
{
distance temp;
temp=p.inches+p.feet;
return temp;
}
void show()
{
cout<<temp;
}
};
int main()
{
distance d;
d.show();
getch();
}
May 31, 2016 at 5:43pm
line 15: operator is misspelled.

line 15: ++ is the increment operator. You can't increment by a distance.

Line 17: You can't assign the sum of two ints to a object of type distance (temp).

Line 17: You're combining two dissimilar measures (inches and feet). If you're overloading the + operator, you need to add feet to feet and inches to inches and allow for overflow of inches.

Line 27: temp is not in scope.

Line 33: You're using the default constructor so both values will be 0.

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
#include <iostream>
#include <conio.h>
using std::cout;
using std::endl;

class distance
{   int inches;
    int feet;

public:
    distance()
    {   inches=0;
        feet=0;
    }

    distance operator + (const distance & p)
    {   distance temp;
        temp.feet = feet + p.feet;
        temp.inches = inches + p.inches;
        if (temp.inches > 12) 
        {   temp.feet++;
            temp.inches -= 12;
        } 
        return temp;
    }

    void show()
    {   cout << feet << "' " << inches << '"' << endl;
    }
};

int main()
{   distance d;
    d.show();
    getch();
}


PLEASE USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.
Topic archived. No new replies allowed.