C++ 操作数到标准运算符的隐式转换

标签 c++ visual-c++ operators implicit-conversion

我在理解 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 发生的情况。 , 其中CharTwchar_t而不是 char .同样operator<<只要您使用合适的流,就可以工作。

当你写 cout << sc ,考虑了特定的过载。然后拒绝该重载,因为编译器无法推断出要用于 CharT 的类型。和其他人。如果它已经知道将执行转换,则它只能推断出类型,但转换尚未被考虑,它们只会在稍晚的阶段进行检查。

如果有一个非模板 operator<<过载 std::string ,然后它会工作,sc将被隐式转换。

关于C++ 操作数到标准运算符的隐式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40941728/

相关文章:

c++ - 在QT中释放动态分配的内存

c++ - pcap_next 调用填充 pcap_pkthdr,其中 len 等于零

c++ - 带有 Visual Studio 2012 的 TCC

linux - 哪个IDE工具可以方便地将.dll工程(VC开发的)转成linux平台的.so工程

c++ - const QString& 的显式模板特化导致未解析的外部

c++ - 当我将 int 添加到 char ('a' + 1 时调用哪个 operator+ 函数)

r - 在 R 中,如何将整个命令行放入二元运算符的 sys.call() 中?

c++ - 如何在 Row Major Order 中声明 3D Array?

c++ - 跨线程扩展 MSVC 2005 的运算符 << 时出现性能问题

javascript - Javascript如何实现日期比较运算符?