首先,我使用的用户定义的转换功能,以隐式转换的目的是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)
为什么在第二种情况下不会发生隐式转换.