Reputation: 12920
How can I modify the following code in such way I don't need to repeat f2=11;
f3=12;
in the main function. The code is for overloading the most common operators.
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;
}
Upvotes: 0
Views: 146
Reputation: 361762
@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 of Double
(the implementation of FLOAT
would be similar).
class Double {
double data;
public:
Double (double p=0.0) : data(p){}
double value() { return data; }
Double & operator+=(Double const & other)
{
data += other.data;
return *this;
}
Double & operator-=(Double const & other)
{
data -= other.data;
return *this;
}
//...
};
Note that you don't need to implement operator=(Double const&)
and Double(Double const&)
. The compiler generated ones would be enough. Since the constructor takes one argument of type double
, you don't need to implement operator=(double const &)
also. The compiler generated copy-semantics, along with the constructor, would take care of that.
Now see this,
//implement operator+ and operator- as non-member functions
Double operator+(Double a, Double const & b)
{
a += b; //a is local copy, so we can change it
return a;
}
Double operator-(Double a, Double const & b)
{
a -= b; //a is local copy, so we can change it
return a;
}
Note that I've implemented operator+
and operator-
in terms of operator+=
and operator-=
respectively.
Similarly, you can implement operator/=
and operator*=
as member functions, and then implement operator/
and operator*
in terms of the them!
Upvotes: 3
Reputation: 272762
Your operators should create a new instance; they shouldn't be modifying themselves (in fact, they should be declared const
to prevent this).
e.g.:
FLOAT operator+(FLOAT obj) const
{
FLOAT tmp;
tmp.setFloat(x + obj.x);
return tmp;
}
Note there are much more idiomatic ways of defining operator overloads (e.g. defining operator+
in terms of operator+=
, and defining a constructor that takes a float
). But the above should suffice.
Upvotes: 2