我正在编写一个我想将其转换为字符串的类。
我应该这样做吗:
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/