Problem in making operator overloading function a friend of class

I am trying to create a program which will have two classes of rational and complex numbers. I made two global functions for their addition and then made those functions friend of both the classes.
While the friend syntax worked fine for the Rational class, it is giving some error in Complex class due to which I am getting an error whenever I try to access the data members of complex class in that function.
Can anyone help in identifying that error, please? Thank you!
Here's the code.

(Just to be clear, I am getting errors at Line 42, 43, 49, and 50)
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
#include<iostream>
using namespace std;
class complex
{
	friend complex operator + (complex c, rational r);
	friend rational operator + (rational r, complex c);
protected:
	int real;
	int img;
public:
	complex(int a, int b)
	{
		real = a;
		img = b;
	}
	complex()
	{
		real = 0; img = 0;
	}

};
class rational
{
protected:
	int x;
	int y;
public:
	rational(int a, int b)
	{
		x = a;
		y = b;
	}
	rational()
	{
	}
	friend complex operator + (complex c, rational r);
	friend rational operator + (rational r, complex c);
};
rational operator + (rational r, complex c)
{
	rational result;
	result.x = r.x + c.real;
	result.y = r.y + c.img;
	return result;
}
complex operator + (complex c, rational r)
{
	complex res;
	res.real = r.x + c.real;
	res.img = r.y+c.img;
	return res;
}

int main()
{
	rational r(3, 4), r1;
	complex c(3, 5), c1;
	r1 = r + c;

	c1 = c + r;

	system("pause");
}
Last edited on
> Just to be clear, I am getting errors at Line 42, 43, 49, and 50
if you just bothered to paste the errors...
you are getting an error on line 5 and 6
foo.cpp|5 col 40| error: ‘rational’ has not been declared
foo.cpp|6 col 9| error: ‘rational’ does not name a type; did you mean ‘atoll’?

at that point the compiler has no idea what `rational' may be, you need to forward declare it.
1
2
3
class rational; //line 3, note the semicolon
class complex{
//... 



also, your addition doesn't seem quite right
Oh, didn't notice that. Thanks for pointing it out ^_^

There were actually too many errors to paste them here :| so I instead decided to only mention those lines where there was underlined syntax indicating an error.


As for addition function, yes, will work on that :P it's just a start... Thank you.
When confronted by a list of errors one line of attack to fixing them is work from the top down, one error at a time.

More often than not, as ne555 points out, fixing earlier errors fixes errors further down the list.

Say you have 80+ errors; fix the top listed error and 18 errors go away.
Topic archived. No new replies allowed.