A unary operator for a class can be overloaded as a non-static member function with no arguments or as a global function with one argument; that argument must be either an object of the class or a reference to an object of the class. Member functions that implement overloaded operators must be non-static so that they can access the non-static data in each object of the class. Remember that static member functions can access only static data members of the class.
Later in this chapter, we will overload unary operator ! to test whether an object of the String class we create (Section 11.10) is empty and return a bool result. Consider the expression !s, in which s is an object of class String. When a unary operator such as ! is overloaded as a member function with no arguments and the compiler sees the expression !s, the compiler generates the call s.operator!(). The operand s is the class object for which the String class member function operator! is being invoked. The function is declared in the class definition as follows:
class String { public: bool operator!() const; ... }; // end class String
A unary operator such as ! may be overloaded as a global function with one argument in two different wayseither with an argument that is an object (this requires a copy of the object, so the side effects of the function are not applied to the original object), or with an argument that is a reference to an object (no copy of the original object is made, so all side effects of this function are applied to the original object). If s is a String class object (or a reference to a String class object), then !s is treated as if the call operator!( s ) had been written, invoking the global operator! function that is declared as follows:
bool operator!( const String & );
Introduction to Computers, the Internet and World Wide Web
Introduction to C++ Programming
Introduction to Classes and Objects
Control Statements: Part 1
Control Statements: Part 2
Functions and an Introduction to Recursion
Arrays and Vectors
Pointers and Pointer-Based Strings
Classes: A Deeper Look, Part 1
Classes: A Deeper Look, Part 2
Operator Overloading; String and Array Objects
Object-Oriented Programming: Inheritance
Object-Oriented Programming: Polymorphism
Templates
Stream Input/Output
Exception Handling
File Processing
Class string and String Stream Processing
Web Programming
Searching and Sorting
Data Structures
Bits, Characters, C-Strings and structs
Standard Template Library (STL)
Other Topics
Appendix A. Operator Precedence and Associativity Chart
Appendix B. ASCII Character Set
Appendix C. Fundamental Types
Appendix D. Number Systems
Appendix E. C Legacy Code Topics
Appendix F. Preprocessor
Appendix G. ATM Case Study Code
Appendix H. UML 2: Additional Diagram Types
Appendix I. C++ Internet and Web Resources
Appendix J. Introduction to XHTML
Appendix K. XHTML Special Characters
Appendix L. Using the Visual Studio .NET Debugger
Appendix M. Using the GNU C++ Debugger
Bibliography