Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simple c++: How to overload the multiplication operator so that float*myClass and myClass*float works

class MyClass;

int main()
{
  float a = 5;
  MyClass c1;
  MyClass c2 = a*c1;
  MyClass c3 = c1*a;
}

How can I overload the multiply operator so that both a*c1 and c1*a work?

like image 665
user52343 Avatar asked Apr 27 '12 17:04

user52343


People also ask

Can you overload operators in C?

No, it is not possible. C does not support operator overloading by the developer.

How do you overload the operator?

Overloading Binary Operators Suppose that we wish to overload the binary operator == to compare two Point objects. We could do it as a member function or non-member function. To overload as a member function, the declaration is as follows: class Point { public: bool operator==(const Point & rhs) const; // p1.

What is operator overloading with example?

This means C++ has the ability to provide the operators with a special meaning for a data type, this ability is known as operator overloading. For example, we can overload an operator '+' in a class like String so that we can concatenate two strings by just using +.

Which function is used to overload the operator?

An overloaded operator is called an operator function. You declare an operator function with the keyword operator preceding the operator. Overloaded operators are distinct from overloaded functions, but like overloaded functions, they are distinguished by the number and types of operands used with the operator.


1 Answers

Like so:

MyClass operator* (float x, const MyClass& y)
{
    //...
}

MyClass operator* (const MyClass& y, float x)
{
    //...
}

The second one can also be a member function:

class MyClass
{
    //...
    MyClass operator* (float x);
};

The first 2 options work as declarations outside of class scope.

like image 160
Luchian Grigore Avatar answered Oct 19 '22 20:10

Luchian Grigore