Tom*_*auz 4 c++ oop c++11 c++14
我正在编写一个要转换为字符串的类。
我应该这样做吗:
std::string toString() const;
Run Code Online (Sandbox Code Playgroud)
或者像这样:
operator std::string() const;
Run Code Online (Sandbox Code Playgroud)
什么样的方式更受欢迎?
在标准库中具有“字符串”表示形式的类(例如 std::stringstream).str()用作成员函数来返回文本。如果您也希望能够将您的类用于通用代码,最好使用相同的约定(toString是“ Javanese ”和ToString“ Sharpish ”)。
关于使用转换操作符的,如果你的类是专门设计的互通与字符串表达式字符串(转换为字符串,其实是一个“促销”,像这使得只感觉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
Run Code Online (Sandbox Code Playgroud)
如果您的类与字符串无关,而只需要参与 I/O,那么请考虑不转换为字符串,而是写入流的想法,通过...
friend std::ostream& operator<<(std::ostream& stream, const yourclass& yourclass)
Run Code Online (Sandbox Code Playgroud)
这样你就可以做...
std::cout << a;
std::stringstream ss;
ss << a; // this makes a-to-text, even respecting locale informations.
Run Code Online (Sandbox Code Playgroud)
...也许甚至不需要分配任何与字符串相关的内存。