|
Every class in Java inherits a method called toString() from the root class Object that, if overridden, allows a print method such as System.out.print to directly print out an object of that class. In the following example, instead of equipping User with a print method as we did before, we now provide it with an override definition for the toString method in line (A).
//PrintObj.java class User { private String name; private int age; public User( String str, int yy ) { name = str; age = yy; } public String toString() { //(A) return "Name: " + name + " Age: " + age; } } class Test { public static void main( String[] args ) { User us = new User( "Zaphod", 119 ); System.out.printin( us ); // Name: Zaphod Age: 119 //(B) } }
As a result, we can now directly supply a User argument to the System.out.println method in class Test, as we show in line (B).
We could use the same strategy in a C++ program; that is, equip a class with a toString()-like function that creates a string representation from the values of the data members of the class. The string thus constructed could then be output by, say, the usual output operator ‘<<’. However, a more common way to create print representations in C++ is to overload the output operator directly for a class, as we do in the example below in line (C). The syntax used will make sense after we have discussed the friend declaration in Section 3.11 of this chapter and operator overloading in Chapter 12. From the syntax shown in line (D), note how the operator overload definition of line (C) allows us to use a User object directly as an operand for the output operator.
//PrintObj.cc #include <iostream> #include <string> using namespace std; class User { string name; int age; public: User( string str, int yy ) { name = str; age = yy; } friend ostream& operator<<(ostream& os, const User& user) { //(C) os << "Name: " << user.name << " Age: " << user.age << endl; } }; int main() { User us( "Zaphod", 119 ); cout << us << endl; // Name: Zaphod Age: 119 //(D) return 0; }
|