有一个标准的方法来将类转换为字符串 [英] Is there a standard way to convert a class to a string
问题描述
在Java中,标准是定义方法 toString()
以返回类的字符串表示形式。除了重载运算符<<
,C ++中有这样的标准吗?我知道有 std :: to_string()
方法来获取数字的字符串表示。 C ++标准是说定义方法 to_string()
来为类提供类似的目的,还是C ++程序员遵循的惯例?
In Java, the standard is to define the method toString()
to return a string representation of a class. Other than overloading operator<<
, is there any such standard in C++? I know there are the std::to_string()
methods to get a string representation of a number. Does the C++ standard speak of defining the method to_string()
to serve similar purpose for a class, or is there a common practice followed by C++ programmers?
推荐答案
做这种事情的标准方法是提供一个插入操作符,以便一个对象可以插入到
The standard way to do this kind of thing is to provide an insertion operator so that an object can be inserted into a stream -- which may be any kind of stream, such as a stringstream.
如果你愿意,你还可以提供一个转换为字符串的方法(对你的插入运算符),如果发现转换可以接受,可以提供一个'to string'运算符。
If you wish, you can also provide a method that converts to a string (useful for your insertion operator), and, if you find the conversion acceptable, you can provide a 'to string' operator.
这是我的标准'point'类示例:
Here's my standard 'point' class example:
template <typename T>
struct point
{
T x;
T y;
point(): x(), y() { }
point( T x, T y ): x(x), y(y) { }
};
template <typename T>
std::ostream& operator << ( std::ostream& outs, const point <T> & p )
{
return outs << "(" << p.x << "," << p.y << ")";
}
我还倾向于保持一个方便的函数将事物转换为字符串: / p>
I also tend to keep a handy function around to convert things to strings:
template <typename T>
std::string to_string( const T& value )
{
std::ostringstream ss;
ss << value;
return ss.str();
}
现在我可以轻松使用:
int main()
{
point p (2,-7);
std::cout << "I have a point at " << p << ".\n";
my_fn_which_takes_a_string( to_string(p) );
您会发现 Boost Lexical Cast Library 也是为这类事物设计的。
You'll find that the Boost Lexical Cast Library is also designed for this kind of thing.
。
这篇关于有一个标准的方法来将类转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!