Learn Operator Overloading
Explore how operator overloading allows you to define custom behaviors for operators on user-defined types in D. Understand the use of function templates like opOpAssign to support operators such as += with structs and classes, helping you write clearer and more intuitive code.
We'll cover the following...
Operator overloading
Most of the topics covered in this chapter apply to classes as well. The biggest difference is that the behavior of the assignment operation opAssign() cannot be overloaded for classes.
Operator overloading involves many concepts, some of which will be covered later in the course (templates, auto ref, etc.). For that reason, you may find this chapter to be harder to follow than the previous ones. Operator overloading enables us to define how user-defined types behave when used with operators. In this context, the term overload means providing the definition of an operator for a specific type.
We have seen how to define structs and their member functions in previous chapters. As an example, we have defined the increment() member function to be able to add Duration objects to TimeOfDay objects. Here are the two structs from previous chapters:
A benefit of ...