我在理解 C++ 将使用隐式转换的条件时遇到一些问题。假设我有一个类:
class SomeClass
{
private:
int val;
public:
SomeClass(int i) :val{ i } {}
operator string() { return to_string(val); }
};
为什么在将此类与运算符一起使用时我需要转换为字符串?为什么它不隐式执行转换?
代码:
int main(void)
{
SomeClass sc = 4;
cout << (string)sc << endl; //prints 4, compiles fine
cout << sc << endl;//does not compile, no operator "<<" matches these operands
string str1 = sc;//compiles fine, performs cast
string str2 = "Base String" + sc;//does not compile, no operator "+" matches these operands
}
这个问题的学术性多于实际性,因为无论如何只使用强制转换更具可读性。
最佳答案
operator<<
overload当你写 cout << (string)sc
时会用到是一个函数模板:
template <class CharT, class Traits, class Allocator> std::basic_ostream<CharT, Traits>& operator<<(std::basic_ostream<CharT, Traits>& os, const std::basic_string<CharT, Traits, Allocator>& str);
这是因为 std::string
本身是一个类模板,可以用 char
以外的其他类型实例化, 如果字符被写入相同字符类型的流中,应该仍然是可打印的。事实上,这正是 std::wstring
发生的情况。 , 其中CharT
是wchar_t
而不是 char
.同样operator<<
只要您使用合适的流,就可以工作。
当你写 cout << sc
,考虑了特定的过载。然后拒绝该重载,因为编译器无法推断出要用于 CharT
的类型。和其他人。如果它已经知道将执行转换,则它只能推断出类型,但转换尚未被考虑,它们只会在稍晚的阶段进行检查。
如果有一个非模板 operator<<
过载 std::string
,然后它会工作,sc
将被隐式转换。
关于C++ 操作数到标准运算符的隐式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40941728/