18. Operator Functions: Doing It with Class

One of the more interesting things you can do with C++ is to define how operators work with objects of your classes. You can define a Fraction type, for example, and then create a way for the following statements to be meaningful in C++:

Fraction fr1(1, 2), fr2(1, 4);cout << fr1 + fr2 << endl;

Wouldn’t it be nice if this would add 1/2 to 1/4 and then print the characters “3/4”? Well, you can make C++ do just that. And you can make such code even more readable by adding the Fraction(string) constructor shown at the end of Chapter 11. In that case, you can write this:

Fraction a = "1/2", b = "1/6";cout << a + b << endl;   // Print "2/3".

In this ...

Get C++ Without Fear: A Beginner’s Guide That Makes You Feel Smart, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.