Operator Overloading

Operator Overloading - x = e3; cout...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
Operator Overloading Suppose that you are using an enumeration and you wish to output its value: enum E {e = 37}; cout << e; 37 will indeed be output, by virtue of the enumerator value being promoted to an int and then output using the operator<<(int) function found in iostream.h. But what if you're interested in actually seeing the enumerator values in symbolic form? One approach to this would be as follows: #include <iostream.h> enum E {e1 = 27, e2 = 37, e3 = 47}; { char* s; switch (e) { case e1: s = "e1"; break; case e2: s = "e2"; break; case e3: s = "e3"; break; default: s = "badvalue"; break; } return os << s; } main() { enum E x;
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: x = e3; cout &lt;&lt; x &lt;&lt; &quot;\n&quot;; cout &lt;&lt; e1 &lt;&lt; &quot;\n&quot;; cout &lt;&lt; e2 &lt;&lt; &quot;\n&quot;; cout &lt;&lt; e3 &lt;&lt; &quot;\n&quot;; cout &lt;&lt; E(0) &lt;&lt; &quot;\n&quot;; return 0; } In the last output statement, we created an invalid enumerator value and then output it. Operator overloading in C++ is very powerful but can be abused. It's quite possible to create a system of operators such that it is difficult to know what is going on with a particular piece of code. Some uses of overloaded operators, such as for array indexing with subscript checking, -&gt; for smart pointers, or + - * / for doing arithmetic on complex numbers, can make sense, while other uses may not....
View Full Document

Page1 / 2

Operator Overloading - x = e3; cout...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online