ambiguous symbol error using overloaded operator+

May 11, 2010 at 8:21pm
This is a pretty basic program to learn how to use overloaded operators (specifically + in this case). I want to be able to add distances of miles, feet, and inches together and make sure they are printed in the correct format (i.e. inches never go above 11).

I'm getting "error C2872; 'distance' : ambiguous symbol" errors for lines 34 and 46, any idea what's wrong?

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
#include <iostream>
using namespace std;

class distance
{
private:
	int mi, ft, in;
	void simplify();
public:
	distance(int m=0, int f=0, int i=0)
		{ mi=m; ft=f; in=i; simplify(); }
	void setdata(int m,int f, int i)
		{ mi=m;	ft=f; in=i; simplify(); }
	int getmi()
		{return mi;}
	int getft()
		{return ft;}
	int getin()
		{return in;}
	distance operator+(const distance &) const;
};

void distance::simplify()
{
	in = 12*ft + in;
	ft = in / 12;
	in = in % 12;
	ft = 5280*mi + ft;
	mi = ft / 5280;
	ft = ft % 5280;
	
}

distance distance::operator+(const distance &right) const
{
	distance temp;
	temp.in = in + right.in;
	temp.ft = ft + right.ft;
	temp.mi = mi + right.mi;
	temp.simplify();
	return temp;
}

int main()
{
	distance d1, d2, d3;
	int m, f, i;

	cout << "enter a distance in mi, ft and in: ";
	cin >> m >> f >> i;
	d1.setdata(m,f,i);
	cout << "enter another distance: ";
	cin >> m >> f >> i;
	d2.setdata(m,f,i);
	d3 = d1 + d2;
	cout << "d1 + d2 = " << d3.getft() << "ft " << d3.getin() << "in " << endl;
	return 0;
}
Last edited on May 11, 2010 at 8:30pm
May 11, 2010 at 8:43pm
Somewhere in one of a forums is a thread about the hazards of using the using namespace directive.
It brings in a lot of stuff from the std namespace and you can end up naming one of your functions
or class with a name that already exists - this is what has happened in your case.

You will find that if you comment out the line
//using namespace std; //comment out

You will find that the errors relating to distance should dissapear.

But in the main function you will get errors with cout and cin - just change those
to std::cout and std::cin


Links:
http://www.cplusplus.com/doc/tutorial/namespaces/
Last edited on May 11, 2010 at 8:45pm
May 11, 2010 at 9:11pm
wow that's all it was haha. I changed distance to Distance and it complied
Topic archived. No new replies allowed.