I'm new to programming and I'm having a problem with an assignment I was given to add complex numbers.
When I run the code it always points to these sections of code stating that a and b are private. I am guessng it is because am usng the complex type within the complex class.
Could somebody give me an idea as to where I'm going wrong.
Thanks
1 2 3 4 5 6 7 8 9
class complex
{
float a, b;
public:
void input(float real, float img);
void display(complex c);
complex sum(complex, complex);
};
The above poster is correct, if you want to add two objects together like this you should overload the addition operator. Try googling "c++ overload operator". After overloading the add operator you can do stuff like:
1 2
// c1 and c2 are complex
complex c3 = c1 + c2;
instead of:
complex c3 = c1.sum( c1, c2 );
At the very least, if you don't overload the addition operator, make the function static.
I agree, overloading the + operator is way better and easier to use afterward. A few months ago I made, for fun, a class named complex.h. It was getting right to the point of overloading operators. I just wanted to remember such things hehe, so anyway you wanna see it ? I know it is quite not good for your learnings... :D
That should be ok, though. sum() is a member function of complex, and should therefore be able to access the private data members of its own instance or of any other instance of complex passed in.
Anyway, I tend to follow the rule of making non-public things protected rather than private unless there is a strong reason why derived classes should not have direct access to the members.