How can I modify the following code in such way I don’t need to repeat f2=11; in the main function. The code is for overloading the most common operators.
f3=12;
class FLOAT{
private:
float x;
public:
FLOAT(){ x=0.0; }
void setFloat(float f) { x=f; }
float getFloat() { return x;};
FLOAT operator+(FLOAT obj) {x=x+obj.x; return *this;};
FLOAT operator-(FLOAT obj) {x=x-obj.x; return *this;};
FLOAT operator*(FLOAT obj) {x=x*obj.x; return *this;};
FLOAT operator/(FLOAT obj) {x=x/obj.x; return *this;};
FLOAT& operator=(const FLOAT& obj) {this->x=obj.x; return *this; };
FLOAT& operator=(const float& y) {this->x=y; return *this; };
};
int main() {
FLOAT f,f2,f3;
f2=11;
f3=12;
f=f3-f2;
cout<<"f3-f2 ="<<f.getFloat()<<endl;
f2=11;
f3=12;
f=f3+f2;
cout<<"f3+f2 ="<<f.getFloat()<<endl;
f2=11;
f3=12;
f=f3*f2;
cout<<"f3*f2 ="<<f.getFloat()<<endl;
f2=11;
f3=12;
f=f3/f2;
cout<<"f3/f2 ="<<f.getFloat()<<endl;
system("pause"); // to pause console screen
return 0;
}
@Oli’s answer pretty much says you what minimal thing you need to do in order to make your code work. However, I see (and I know even @Oli sees) that your implementation of the class has many flaws.
Since you’ve implemented
FLOAT, I’m explaining you the implementation ofDouble(the implementation ofFLOATwould be similar).Note that you don’t need to implement
operator=(Double const&)andDouble(Double const&). The compiler generated ones would be enough. Since the constructor takes one argument of typedouble, you don’t need to implementoperator=(double const &)also. The compiler generated copy-semantics, along with the constructor, would take care of that.Now see this,
Note that I’ve implemented
operator+andoperator-in terms ofoperator+=andoperator-=respectively.Similarly, you can implement
operator/=andoperator*=as member functions, and then implementoperator/andoperator*in terms of the them!