c++ - toString 函数或 (std::string) 在 C++ 中强制转换重载

标签 c++ oop c++11 c++14

我正在编写一个我想将其转换为字符串的类。

我应该这样做吗:

std::string toString() const;

或者像这样:

operator std::string() const;

哪种方式更容易被接受?

最佳答案

标准库中具有“字符串”表示的类(例如 std::stringstream)使用 .str() 作为成员函数来返回文本。如果您也希望能够将您的类用于通用代码,最好使用相同的约定(toString 是“Javanese”和ToString尖锐”)。

关于转换运算符的使用,仅当您的类专门设计用于与字符串表达式中的字符串交互时才有意义(转换为字符串实际上是一种“提升”,如 int 隐含地成为 long)。

如果您的类“降级”为字符串(在这样做时丢失信息),最好让转换运算符显式(explicit operator std::string() const)。

如果它与字符串语义无关,并且只是偶尔需要转换,请考虑显式命名函数。

请注意,如果 a 是一个变量,您必须考虑其用法的语义是:

a.str();       // invoking a member function 
               // mimics std::stringstream, and std::match_results 

to_string(a);  // by means of a free function 
               // mimics number-to-text conversions 

std::string(a) // by means of an explicit cast operator 
               // mimics std::string construction

如果你的类与字符串无关,而只是参与 I/O,那么考虑不转换为字符串,而是写入流的想法,通过...

friend std::ostream& operator<<(std::ostream& stream, const yourclass& yourclass)

这样你就可以...

std::cout << a;

std::stringstream ss;
ss << a;   // this makes a-to-text, even respecting locale informations.

...甚至可能不需要分配任何与字符串相关的内存。

关于c++ - toString 函数或 (std::string) 在 C++ 中强制转换重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41199847/

相关文章:

c++ - 如何使用带有 lambda 仿函数参数的 requires 子句?

c++ - 为什么编译器提示这不是一个 constexpr?

c++ - 在 boost::spirit::lex 中,第一次解析花费的时间最长,后续解析的时间会短得多

c# - 处理数字范围

Python键入TypeVar(A,B,covariant = True)是什么意思?

c++ - 阅读 C++ ifstream 两次?

c++ - 如何将 unique_ptr 的 move 构造函数和运算符实现为类的私有(private)成员

c++ - 将 fpu 异常或 inf 投入工作是否可能/有效?

c++ - 我可以对我的 conan 包的用户隐藏我的链接标志吗?

php - 具有返回类型和 SOLID 的接口(interface)