是否有将类转换为字符串的标准方法

Ahm*_*d A 9 c++ c++11

在Java中,标准是定义toString()返回类的字符串表示的方法.除了重载operator<<,C++中是否有这样的标准?我知道有一些std::to_string()方法可以获得数字的字符串表示.C++标准是否谈到定义to_string()为类提供类似目的的方法,或者C++程序员是否遵循通用的做法?

Dút*_*has 7

执行此类操作的标准方法是提供插入操作符,以便可以将对象插入到流中 - 可以是任何类型的流,例如字符串流.

如果您愿意,还可以提供转换为字符串的方法(对插入运算符很有用),如果发现转换可以接受,则可以提供"to string"运算符.

这是我标准的'点'类示例:

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 << ")";
}
Run Code Online (Sandbox Code Playgroud)

我还倾向于保留一个方便的函数来将事物转换为字符串:

template <typename T>
std::string to_string( const T& value )
{
  std::ostringstream ss;
  ss << value;
  return ss.str();
}
Run Code Online (Sandbox Code Playgroud)

现在我可以轻松使用它:

int main()
{
  point p (2,-7);

  std::cout << "I have a point at " << p << ".\n";

  my_fn_which_takes_a_string( to_string(p) );
Run Code Online (Sandbox Code Playgroud)

你会发现Boost Lexical Cast Library也是为这种东西而设计的.

希望这可以帮助.


R S*_*ahu 1

C++ 标准是否谈到定义方法 to_string() 来为类提供类似的目的,

不。

或者 C++ 程序员是否遵循一种常见的做法。

不。但是,我怀疑每个项目都有类似的功能。名称和返回类型很可能取决于项目的编码指南。

在我的工作中,我们使用

virtual QString toString() const = 0;
Run Code Online (Sandbox Code Playgroud)

在我们的一个基类中。

您可以开始在您的项目中使用类似的东西。

virtual std::string toString() const = 0;
Run Code Online (Sandbox Code Playgroud)

在你的基类中。