| Paul 的个人资料Paul's Space照片日志列表 | 帮助 |
Paul's Space |
||||
|
9月24日 Formatting to a C++ ostreamFormatting a data type in C++ using an ostream is not complicated. All that is really needed is a an appropriate operator << override. I do this a lot for debugging new programs. I'll often write an operator << overload for every type I define, even if I throw away the operator << overloads later. Let's do an example for how to do this with an enumeration. Here is an enumeration: enum MyEnumeration { The key is knowing what the parameters and return value need to be for the operator << override. The return value needs to be a reference to an ostream, as does the first parameter. The second parameter needs to be a const reference to the type to be formatted. (It doesn't absolutely have to be a reference. If it isn't const, you won't be able to print const's.) For MyEnumeration: std::ostream &operator << (std::ostream &os, const MyEnumeration &en) Now we can print a MyEnumeration like this: MyEnumeration me = AnotherValue; We can format any type in an alternative manner by defining a tiny class with a constructor and a friend function that is our operator << override. As an example let's see how to format unsigned integers in base 5. class BaseFive { std::ostream &operator << (std::ostream &os, const BaseFive &bf) Now we can print an unsigned int in base 5 like this: std::cout << BaseFive(125) << std::endl; A more complex class can be formatted by having an appropriate friend function for our operator << override. Here are the highlights: class SomeClass { Now we can print instances of SomeClass like this: SomeClass aSomeClass, anotherSomeClass; 4月27日 ExplanationsLike space pictures? Don’t like to wait too long? Here you
go. Who says you can’t get good pictures with MS Paint? I don’t know what it is, but if you need to know how it
works this guy explains it in detail. |
||||
|
|