小编Zip*_*Sun的帖子

为什么隐式转换为std :: string不适用于operator <<被调用

首先,我使用的用户定义的转换功能,以隐式转换的目的是int,然后将其插入至cout<<运营商.程序编译成功并打印为"0".

#include <iostream>

using namespace std;

class T {
public:
    operator int () {
        return 0;
    }
};

int main()
{
    T a;
    cout << a << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

然后,我尝试做同样的事情,除了对象被转换为std::string.该程序出现编译错误.

#include <iostream>
#include <string>

using namespace std;

class T {
public:
    operator string () {
        return "";
    }
};

int main()
{
    T a;
    cout << a << endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

为什么在第二种情况下不会发生隐式转换.

c++ type-conversion implicit-conversion

1
推荐指数
1
解决办法
65
查看次数

标签 统计

c++ ×1

implicit-conversion ×1

type-conversion ×1