Using the C++ Math Library    

Defining Your Own Operators

Defining your own operator in C++ is called ``overloading an operator.'' Strictly speaking, you cannot define a new operator; you can only provide an alternative definition for an existing operator. The set of operators that you can overload is limited to the set recognized by C++ but not defined by the MATLAB C++ Math Library.

For example, C++ does not recognize the character sequence ** as an operator. If you try to define operator**() to mean exponentiation, the compiler will issue a syntax error. However, you can define a matrix equivalent for any recognized operator that is missing from the library. You define it in terms of the operators that do come with the library. See Chapter 11 for a complete list of the operators.

Defining matrix equivalents for the additional operators that C++ defines is a simple process. The following example illustrates the proper way to define a new operator.

Assume that you want to define operator*=(), which combines the multiplication and assignment operations. Because the library predefines operator*() and operator=(), building operator*=() is straightforward.

The above code overloads operator*=() for matrix arguments. It is important, in this case, to return the modified matrix, so that you can concatenate the operator with other operators, for example, C = A *= B;. Although the coding style of this example is poor, the code is legal.

When you overload an operator in C++, you cannot change the arity (number of operands) or precedence of the operator. For example, the C++ language definition restricts operator+() to two arguments. You cannot define an operator+() that takes three arguments and returns the sum of all three. Similarly, you cannot change the precedence of operator+() to make the addition in the expression a+b*c occur before the multiplication. Use parentheses to change operator precedence on an expression-by-expression basis. For more information on overloading operators, consult a C++ reference guide.


 Using the Operators Printing, Exceptions, and Memory Management