{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

Operator Overloading

Operator Overloading - x = e3 cout<<...

Info icon This 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}; ostream& operator<<(ostream& os, E e) { 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;
Image of page 1

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

View Full Document Right Arrow Icon
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 << x << "\n"; cout << e1 << "\n"; cout << e2 << "\n"; cout << e3 << "\n"; cout << E(0) << "\n"; 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, -> for smart pointers, or + - * / for doing arithmetic on complex numbers, can make sense, while other uses may not....
View Full Document

{[ snackBarMessage ]}

What students are saying

  • Left Quote Icon

    As a current student on this bumpy collegiate pathway, I stumbled upon Course Hero, where I can find study resources for nearly all my courses, get online help from tutors 24/7, and even share my old projects, papers, and lecture notes with other students.

    Student Picture

    Kiran Temple University Fox School of Business ‘17, Course Hero Intern

  • Left Quote Icon

    I cannot even describe how much Course Hero helped me this summer. It’s truly become something I can always rely on and help me. In the end, I was not only able to survive summer classes, but I was able to thrive thanks to Course Hero.

    Student Picture

    Dana University of Pennsylvania ‘17, Course Hero Intern

  • Left Quote Icon

    The ability to access any university’s resources through Course Hero proved invaluable in my case. I was behind on Tulane coursework and actually used UCLA’s materials to help me move forward and get everything together on time.

    Student Picture

    Jill Tulane University ‘16, Course Hero Intern