| Paul 的个人资料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; 引用通告此日志的引用通告 URL 是: http://pscherf.spaces.live.com/blog/cns!3B092CB7298FDE18!194.trak 引用此项的网络日志
|
|
|