I'm new to overloading operators, I did some search and found this helpful article, I wrote my own code like the author did but I get vector vector::operator*(float, vector) must take either zero or one argument
error.
Here is my code:
class vector
{
public:
float x;
float y;
vector(float, float);
float operator$ (vector, vector);
vector operator* (float, vector);
vector operator* (vector, float);
};
vector::vector(float _x = 0, float _y = 0)
{
x = _x;
y = _y;
}
const float vector::operator$ (const vector &v1, const vector &v2)
{
return (v1.x * v2.x) + (v1.y * v2.y);
}
const vector vector::operator* (const float &m, const vector &v)
{
vector ret_val = v;
ret_val.x *= m;
ret_val.y *= m;
return ret_val;
}
const vector vector::operator* (const vector &v, const float &m)
{
return m * vector;
}
My operating system is kubuntu 12.04
and my IDE is dev-C++
running on linux using wine windows program loader.
Operator overloading is a compile-time polymorphism. It is an idea of giving special meaning to an existing operator in C++ without changing its original meaning.
Rules for operator overloading in C++If some operators are not present in C++, we cannot overload them. The precedence of the operators remains same. The overloaded operator cannot hold the default parameters except function call operator “()”. We cannot overload operators for built-in data types.
Overloading Compound Assignment Operators Compound assignment operators cannot be overloaded directly. They will be overloaded if the operator that is compounded is overloaded. For example, if the addition operator “+” is overloaded, “+=” will also be overloaded using the same user method.
4. What is operator overloading in C++? Explanation: Operator overloading helps programmer to give his/her own meaning to an operator for user defined data types(eg, classes).
Because you are defining operator*()
as a member function, there is already one implicit parameter: the object for which the method is invoked! Therefore, member functions take one explicit parameter, not two.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With