[comp.lang.c++] overloading operator+

hocker@enuxha.eas.asu.edu (Charles C. Hocker) (11/10/90)

Hello,
	I am new to c++ and am having a problem trying to overload
the operator+.  What I am trying to do, is I have a structure and I want
to add structures together.

struct p {
	int	X, Y, Z;
};

class pclass {
	public:
		p	pnt;

	pclass (int x, int y, int z);
};

pclass::pclass (int x=0, int y=0, int z=0)
{
	pnt.X = x;
	pnt.Y = y;
	pnt.Z = z;
}

pclass	operator+ (p a, p b)
{
	return p (a.X+b.X, a.Y+b.Y, a.Z+b.Z);
}

int	main (void)
{
	pclass p1 (1, 2, 3),
	       p2 (2, 3, 4),
	       p3;

	p3 = p1 + p2;
}

When compiling this program in TC++, I receive an errors concerning the 
overloading of the operator+.  I am writing a graphics program and I would
like to add points without having to add their respective values.  This, 
by the way, is my first attempt with c++ so I am not quite sure what I 
am doing.  I have referenced both the TC++ manual, and the ARM.

Sincerly   
		Charles C. Hocker
		hocker@enuxha.eas.asu.edu

Bruce.Hoult@actrix.co.nz (Bruce Hoult) (11/11/90)

>When compiling this program in TC++, I receive an errors concerning the
>overloading of the operator+.
 
I don't see why you need the struct type "p".  Confusion between it and
pclass is the root of your problem.  Changing your operator+ function to
 
pclass  operator+ (pclass a, pclass b)
{
        return pclass (a.pnt.X+b.pnt.X, a.pnt.Y+b.pnt.Y,
a.pnt.Z+b.pnt.Z);
}
 
will fix the immediate problem, and make the program execute correctly.