MATLAB Object-Oriented Programming

(Joyce) #1

Operator Overloading


In this section...
“Why Overload Operators” on page 17-47
“How to Define Operators” on page 17-47
“Sample Implementation — Addable Objects” on page 17-48
“MATLAB Operators and Associated Functions” on page 17-50

Why Overload Operators


By implementing operators that are appropriate for your class, you can integrate objects
of your class into the MATLAB language. For example, objects that contain numeric data
can define arithmetic operations like +, *, - so that you can use these objects in
arithmetic expressions. By implementing relational operators, you can use objects in
conditional statements, like switch and if statements.

How to Define Operators


You can implement MATLAB operators to work with objects of your class. To implement
operators, define the associated class methods.

Each operator has an associated function (e.g., the + operator has an associated plus.m
function). You can implement any operator by creating a class method with the
appropriate name. This method can perform whatever steps are appropriate for the
operation being implemented.

For a list of operators and associated function names, see “MATLAB Operators and
Associated Functions” on page 17-50.

Object Precedence in Operations

User-defined classes have a higher precedence than built-in classes. For example,
suppose q is an object of class double and p is a user-defined class. Both of these
expressions generate a call to the plus method in the user-define class, if it exists:

q + p
p + q

Operator Overloading
Free download pdf