Let's say I make a class, like, which contains a char array. Now, what operator handles this:
myCl开发者_如何学编程ass inst;
cout << inst;
At the "cout << inst;" what is called, by simply the class' name? Thanks.
What is called is std::ostream &operator<<(std::ostream &, myClass const &)
. You can overload this if you want.
By creating a friend output operator, as in the following example.
#include <iostream>
class MyClass {
friend std::ostream & operator<<(std::ostream &out, const MyClass &inst);
public:
// ... public interface ...
private:
char array[SOME_FIXED_SIZE];
};
std::ostream & operator<<(std::ostream &out, const MyClass &inst)
{
out.write(inst.array, SOME_FIXED_SIZE);
return out;
}
Please not this makes some assumptions about what you mean by "char array", it is greatly simplified if your char array is actually nul (0 character) terminated.
Update: I will say this is not strictly a return value for the class, but rather a textual representation of the class -- which you are free to define.
The compiler will look for an overload of operator<<
. In particular, it will look for either a member-function overload of std::ostream
(won't exist), or a free function, that you should overload with the following prototype:
std::ostream &operator<< (std::ostream &os, const myClass &x);
You may need to make this a friend of myClass
if you need to access protected/private members.
This results in compiler error, unless you have an overloaded typecast operator for some type that ostream knows. You can add your own types to the types that ostream knows by overloading the global ostream& operator(ostream& os, const myClass& x)
or making your type convertible to a string/int etc. Be careful though, the typecast overloading can shoot you in the foot and is considered a bad practice.
The simplest way is just printing some variables from your class:
myClass inst;
cout << inst.getName() << ": " << inst.getSomeValue();
To be able to use std::cout << someClass
, you have to create an operator like following :
std::ostream &operator<< (std::ostream &, const someClass &);
精彩评论