Summary

This document provides an explanation of operator overloading in C++. It details how to create functions that customize how operators behave when used with custom classes.

Full Transcript

Operator Overloading In C++, you can overload most operators so that they perform special operations relative to the classes that you create. Some operators are overloaded frequently. For example, the C++ language itself overloads + and -, so that these operators perform differently depending on th...

Operator Overloading In C++, you can overload most operators so that they perform special operations relative to the classes that you create. Some operators are overloaded frequently. For example, the C++ language itself overloads + and -, so that these operators perform differently depending on the built-in data type (int, double, float) being used. Also, if you want to use the same operators to perform addition or subtraction of Complex numbers (a class that we mentioned earlier) you can overload + and – so that they perform arithmetic for your own data type. Creating an Overloaded Operator Operators are overloaded by writing a function definition (with a header and body) as you normally would, except that the function name now becomes the keyword operator followed by the symbol being overloaded. For example, the function name operator+ would be used to overload the addition operator (+). For example, if you had a simple class called Arithmetic that performs basic algebraic operations if you wanted to overload + operator so that it works on variables of your own class you would write #include using namespace std; class Arithmetic { public: Arithmetic(int = 1); // constructor Arithmetic operator+(Arithmetic); Arithmetic operator-(Arithmetic); Arithmetic operator/(Arithmetic); Arithmetic operator*(Arithmetic); Arithmetic operator%(Arithmetic); Arithmetic operator++(); void printNumber (){ cout

Use Quizgecko on...
Browser
Browser