为什么 operator<< 不会隐式地将我的自定义 class 对象转换为字符串
Why operator<< does not implicitly converting my custome class object to string
我有一个 class 实现了一个 public string
转换成员函数。当与 operator<<(iostream &, xxx)
结合使用时,我期望我的 class 会自动(隐式)转换为 string
因此适合参数类型。
然而,事实并非如此。为什么,我不想写 operation<<
函数。
#include <string>
#include <iostream>
using namespace std;
struct A {
operator string() { return "asd"; }
};
int main() {
cout << A() << endl; // error
cout << string(A()) << endl; // ok
}
operator<<
for std::string
is a template, and implicit conversion won't be considered in template argument deduction,失败了。
Type deduction does not consider implicit conversions (other than type adjustments listed above): that's the job for overload resolution, which happens later.
正如您所展示的,您可以将 A
显式转换为 std::string
,或者为 A
.
编写 operator<<
我有一个 class 实现了一个 public string
转换成员函数。当与 operator<<(iostream &, xxx)
结合使用时,我期望我的 class 会自动(隐式)转换为 string
因此适合参数类型。
然而,事实并非如此。为什么,我不想写 operation<<
函数。
#include <string>
#include <iostream>
using namespace std;
struct A {
operator string() { return "asd"; }
};
int main() {
cout << A() << endl; // error
cout << string(A()) << endl; // ok
}
operator<<
for std::string
is a template, and implicit conversion won't be considered in template argument deduction,失败了。
Type deduction does not consider implicit conversions (other than type adjustments listed above): that's the job for overload resolution, which happens later.
正如您所展示的,您可以将 A
显式转换为 std::string
,或者为 A
.
operator<<