#include <cmath>
#include <iostream>
usingnamespace std;
#define PI atan(1) * 4;
class Circle {
float radius;
public:
Circle (float);
float getRadius ();
float area ();
Circle operator+ (Circle);
};
Circle::Circle(float radius) {
this->radius = radius;
}
float Circle::getRadius() {
returnthis->radius;
}
float Circle::area() {
returnthis->radius * this->radius * PI;
}
Circle Circle::operator+ (Circle c) {
float newRadius = sqrt((c.area() + this->area()) / PI);
Circle c(newRadius);
return c;
}
int main() {
Circle a(2.0);
Circle b(1.0);
Circle c = a + b;
cout << c.getRadius() << endl;
return 0;
}
The + operator I defined above attempts to add two circles into a big circle with area of the two addend circles combined.
However, I get the following errors upon compilation.
1 2 3 4 5
overloadedOperators.cpp: In member function ‘Circle Circle::operator+(Circle)’:
overloadedOperators.cpp:30: error: expected `)' before ‘;’ token
overloadedOperators.cpp:30: error: expected primary-expression before ‘)’ token
overloadedOperators.cpp:30: error: expected `;' before ‘)’ token
overloadedOperators.cpp:31: error: declaration of ‘Circle c’ shadows a parameter
The first problem is actually in your #define. Try using a constant variable instead.
The second problem is in line 31 where you redefine an object 'c'.
It's best to stay away from macros as they can sometimes cause problems and are nearly impossible to find. This is because the error message will point to a place where it is used instead of the actual macro itself.
Because your macro is expanded into this: ... this->area()) / atan(1) * 4;);
That's where your paranthesis goes and this is part of the reason why everyone is telling you not to use #define for constants. Just don't do it.
The second error in line 31 should be obvious from the error message.
Also, macros are generally dangerous to use, as they don't perform any thinking. They just do what you ask, regardless of whether or not it is valid. That being said, you should only use macros if you REALLY know what you're doing.