This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Operator Overloading in C++ as int + obj
Operator overloading c++-faq
I have a Point object with this operator:
Point operator +(float other) const {
return Point(x + other, y + other, z + other);
}
I can perform addition like so:
point + 10
But I can't perform it in reverse order:
10 + point
Is there another operator I need to overload in order to provide this functionality?
You normally want to overload the global operator:
Point operator+(Point const &a, float b);
Point operator+(float a, Point const &b);
Instead of two overloads, you may want to use only one overload:
Point operator+(Point const &a, Point const &b);
and then have a ctor to create a Point from a float:
class Point {
public:
Point(float);
};
In this case, adding a float to a Point will use the ctor to convert the float to a Point, then use your overloaded operator+ to add those two Points together.
As a free function:
Point operator+(float other, const Point &pt) {
return pt+other;
}
Given an existing Point& Point::operator+=(float other), add these two free functions:
Point operator+(Point pt, float other) {
return pt += other;
}
Point operator+(float other, Point pt) {
return pt += other;
}
Outside of the class:
inline Point operator+(const float& other, const Point& pnt) { return Point(...); };
Related
I'm supposed to do an overloading of the modulus function, but I'm not sure how to do it. Let me know if you require more information.
This is my requirement by my school:
Member function that rotates a Point about the origin by the specified number of degrees. Returns a new Point
Inside the driver file, my school wants the modulus function to accomplish this scenario:
Point pt1(-50, -50);
double angle = 45;
Point pt2 = pt1 % angle;
This is what I've tried:
Point Point::operator%( int value)
{
(int)x%value;
(int)y%value;
return *this;
}
//point.h file
class Point
{
public:
// Constructors (2)
explicit Point(double x, double y);
Point();
double getX() const;
double getY() const;
Point operator+(const Point& other)const ;
Point& operator+(double value);
Point operator*(double value) ;
Point operator%(int value);
Point operator-(const Point& other)const ;
Point operator-(double value);
Point operator^(const Point& other);
Point operator+=(double value);
Point& operator+=(const Point& other) ;
Point& operator++();
Point operator++(int);
Point& operator--();
Point operator--(int);
Point& operator-();
// Overloaded operators (14 member functions)
friend std::ostream &operator<<( std::ostream &output, const Point
&point );
friend std::istream &operator>>( std::istream &input, Point
&point );
// Overloaded operators (2 friend functions)
private:
double x; // The x-coordinate of a Point
double y; // The y-coordinate of a Point
// Helper functions
double DegreesToRadians(double degrees) const;
double RadiansToDegrees(double radians) const;
};
// Point& Add(const Point& other); // Overloaded operators (2 non-member, non-friend functions)
// Point& Multiply(const Point& other);
Point operator+( double value, const Point& other );
Point operator-( double value, const Point& other );
The first error I see is that you didn't respect the requirements of your assignement. Your assignement specifically ask for your type to support this operation:
Point pt1{-50, 50};
Point pt2 = pt1 % 45.5;
This infer that your operator must return a point with the operation apply to it using a double. You clearly store the angle as double, but receive an int. That is not respecting your requirement. Also, you return a rotated point, but not the right one. You're making the operation in-place instead of making the operation on a new point. Inside your operator, you should create a point with the new position. Something like this:
Point Point::operator%(double) const {
return Point{..., ...};
}
Then, your operation is wrong. You cast the point data member to intonly to do a modulo on them. A modulo don't do a rotation. A rotation is usually done with a sine and a cosine. You cannot use the C++ %operator on int to make a rotation.
Suppose I have the following class:
class Point{
private:
int x,y;
public:
int get_x() const {return x;}
int get_y() const {return y;}
Point() :x(0),y(0){}
Point(int x,int y):x(x),y(y){}
Point(const Point& P){
x = P.get_x();
y = P.get_y();
}
Point& operator= (const Point& P) {
x = P.get_x();
y = P.get_y();
return *this;
}
friend ostream& operator<<(ostream& os,const Point& P) {
os<<"["<<P.get_x()<<", "<<P.get_y()<<"]";
return os;
}
Point operator - (const Point &P){
return Point(x-P.get_x(),y-P.get_y());
}
friend bool operator > (const Point &A, const Point &B) {
return A.get_y()>B.get_y();
}
};
Here I used friend function. I can also use function without friend:
class Point{
...
bool operator > (const Point &B) const {
return y>B.get_y();
}
...
};
What are the differences between them in actual implementations? Also in the second method, the code won't compile without 'cont', why is that? Even after I changed the getter function into non-const function, it still won't compile without the 'const'.
As you've already noticed, comparison operator overloads can either be implemented as a member function or as a non-member function.
As a rule of thumb you should implement them as a non-member non-friend function where possible, as this increases encapsulation, and it allows (non-explicit) conversion constructors to be used on either side of the operator.
Say for instance your Point class for whatever reason had an int conversion constructor:
Point(int x);
With a non-member comparison operator you can now do the following:
Point p;
p < 3; // this will work with both a member and non-member comparison
3 < p; // this will **only** work if the comparison is a non-member function
You also seem to be confused about when to use const, again as a rule of thumb for comparison operators you should always use const wherever possible, because comparisons logically do not involve any change to the object.
As Point is a very small class you could also take it by value instead, so in order of most to least preferable your options are:
// Non-member, non-friend
bool operator>(Point const& A, Point const& B);
bool operator>(Point A, Point B);
// Non-member, friend
friend bool operator>(Point const& A, Point const& B);
friend bool operator>(Point A, Point B);
// Member
bool Point::operator>(Point const& B) const;
bool Point::operator>(Point B) const;
This question already has an answer here:
simple c++: How to overload the multiplication operator so that float*myClass and myClass*float works
(1 answer)
Closed 9 years ago.
i'm trying write a polynomial class that can be used for calculation.
class Polynomial
{
public:
Polynomial(QString s); // creates a polynomial with QRegExp
const Polynomial operator+(Polynomial const& rhs); // NOT TESTED
const Polynomial operator+(double d);
const Polynomial operator-(Polynomial const& rhs); //
const Polynomial operator-(double d);
const Polynomial operator-();
private:
void resizeToMin();
QList<int> exp;
QList<double> coeff;
QChar var;
};
i would want to use the Polynomial like this:
Polynomial p("3*x^2 + x^1 -1");
double a = 2.0;
p = p*2 // this works
p = p*a // this works
p = 2*p // DOES NOT WORK
p = a*p // DOES NOT WORK
same for + and -
is this even possible? it would allow me to calculate with polynomials in the same way as with doubles
thanks in advance
Your operators only go one direction as you have them defined. As your class stands, you have the left side always be a Polynomial which won't work for double*Polynomial wherein the double is on the left side.
Since multiplication of polynomials is commutative (I think that's the word...a*b=b*a), you can define an operator like this outside the class:
Polynomial operator+(const double& lhs, const Polynomial& rhs) {
return rhs + lhs; //switch the operation so that the polynomial is on the left hand side
}
It will take in the double as the lefthand side and apply it as if it were the right hand side.
Adapted from this answer: https://stackoverflow.com/a/15741776/1124529
The linked answer also explains a little about doing operations if the operation is not commutative.
When a class overloads operator+, should it be declared const since it does not do any assignment on the object?
Also, I know that operator= and operator+= return a reference because an assignment is made. But, what about operator+? When I implement it should I make a copy of the current object, add the given object to that, and return that value?
Here is what I have:
class Point
{
public:
int x, int y;
Point& operator += (const Point& other) {
X += other.x;
Y += other.y;
return *this;
}
// The above seems pretty straightforward to me, but what about this?:
Point operator + (const Point& other) const { // Should this be const?
Point copy;
copy.x = x + other.x;
copy.y = y + other.y;
return copy;
}
};
Is this a correct implementation of the operator+? Or is there something I am overlooking that could cause trouble or unwanted/undefined behavior?
Better than that, you should make it a free function:
Point operator+( Point lhs, const Point& rhs ) { // lhs is a copy
lhs += rhs;
return lhs;
}
But yes, if you leave it as a member function it should be const as it does not modify the left hand side object.
Regarding whether to return a reference or a copy, the advice for operator overloading is do as fundamental types do (i.e. do as ints do). In this case, addition for two integers returns a separate integer that is not a reference to neither one of the inputs.
This is a very basic operator overload question.
Say I had a class like this...
class xy
{
public:
double x, y;
XY(double X, double Y) { x = X; y = Y;}
XY operator+(const XY & add) const {
return XY(this->x + add.x, this->y + add.y);
}
XY & operator+=(const XY & add) const {?}
}
}
And I want operator+= do to what its supposed to do (you know, add to the current value of x and y). Wouldn't the code be the same for operator+ and operator +=?
How could it be the same? They do different things.
If you don't care about optimizations you can use += in your + operator implementation:
XY operator + (const XY& right) const
{
XY left(*this);
left += right;
return left;
}
Yep, do the add operation (stick to the += operator), and return a reference to itself. Oh, and this can't be a const method.
XY & operator+=(const XY & add) {
this->x += add.x;
this->y += add.y;
return *this;
}
No. Conventionally, operator+ stores the result in a new object and returns it by value, whereas operator+= adds the right-hand side to *this and returns *this by reference.
The two operators are related -- and can often be implemented in terms of one another -- but they have different semantics and therefore can't have identical implementations.