Operator overloadingYou can pretty much do any kind of arithmetic in C++ using the built-in integral and floating-point types. However, that's not always enough. Old-time engineers swear by Fortran, the language which has built-in type complex. In a lot of engineering applications, especially in electronics, you can't really do effective calculations without the use of complex numbers. C++ does not support complex arithmetics. Neither does it support matrix or vector calculus. Does that mean that engineers and scientists should stick to Fortran? Not at all! Obviously in C++ you can define new classes of objects, so defining a complex number is a piece of cake. What about adding, subtracting, multiplying, etc.? You can define appropriate methods of class complex. What about notational convenience? In Fortran you can add two complex numbers simply by putting the plus sign between them. No problem! Enter operator overloading. In an expression like
An equal sign is an operator too. Like most operators in C++, it can be overloaded. Its meaning, however, goes well beyond arithmetics. In fact, if you don't do anything special about it, you can assign an arbitrary object to another object of the same class by simply putting an equal sign between them. Yes, that's right, you can, for instance, do that:
Next. |