I am trying to overload (*,+,-,/,=) opertors in FLOAT class. I wrote this class:
class FLOAT{
private:
float x;
public:
FLOAT(){ x=0.0; }
void setFloat(float f) { x=f; }
void operator+(FLOAT obj) {x=x+obj.x; };
void operator-(FLOAT obj) {x=x-obj.x; };
void operator*(FLOAT obj) {x=x*obj.x; };
void operator/(FLOAT obj) {x=x/obj.x; };
FLOAT& operator=(const FLOAT& obj) {this->x=obj.x; return *this; };
};
and I use it such:
int main() {
FLOAT f,f2,f3;
f.setFloat(4);
f2.setFloat(5);
f3=f+f2;// here is the problem!
system("pause");//to pause console screen
return 0;
}
f3=f+f2 seems not right. What can I do?
I think your implementations of the operators will not do what you want. For example:
Assuming that you change operator+(), for example, to return a FLOAT, you will still have the effect that after the addition, f1 and f3 will both equal 3.0;
A commonly used idiom is to implement the operators like += in the class, and the operators like + outside the class. For example:
…
A side benefit of this is that you can also easily add other operators like
Doing a thorough job on a class like this is good practice for when you want to do this work with more interesting types like complex numbers or matrices. Be sure you add the comparison operators, copy constructor, destructor and assignment operators for completeness. Good luck!