Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading Addition, Subtraction, and Multiplication Operators

How do you go about overloading the addition, subtraction, and multiplication operator so we can add, subtract, and multiply two vectors of different or identical sizes? For example, if the vectors are different sizes we must be able to add, subtract, or multiply the two vectors according to the smallest vector size?

I've created a function that allows you to modify different vectors, but now I'm struggling to overload the operators and haven't a clue on where to begin. I will paste the code below. Any ideas?

def __add__(self, y):     self.vector = []     for j in range(len(self.vector)):         self.vector.append(self.vector[j] + y.self.vector[j])     return Vec[self.vector] 
like image 642
user3014014 Avatar asked Dec 10 '13 23:12

user3014014


People also ask

How do you overload an addition operator?

The name of an overloaded operator is operator x, where x is the operator as it appears in the following table. For example, to overload the addition operator, you define a function called operator+. Similarly, to overload the addition/assignment operator, +=, define a function called operator+=.

Can multiplication operator be overloaded?

@vaisakh you can overload any binary operator if you supply at least a user-defined type. In this case, MyClass is user defined. So you can define operator +(int, const MyClass&) but you can't re-define operator +(int,int) . It works - the operator is scoped to the object to which it is declared.

Which operators are used for overloading?

In the above syntax Return_Type is value type to be returned to another object, operator op is the function where the operator is a keyword and op is the operator to be overloaded. Operator function must be either non-static (member function) or friend function. Overloading unary operator.

What is operator overloading and 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 +.


1 Answers

You define the __add__, __sub__, and __mul__ methods for the class, that's how. Each method takes two objects (the operands of +/-/*) as arguments and is expected to return the result of the computation.

like image 193
jwodder Avatar answered Sep 22 '22 03:09

jwodder