【发布时间】:2020-12-16 23:43:35
【问题描述】:
我有一个类实现了公共string 转换成员函数。当与 operator<<(iostream &, xxx) 结合使用时,我期望我的类会自动(隐式)转换为 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<<采用std::string(或者,准确地说,std::basic_string)是一个模板。模板参数推导过程中不考虑隐式转换。
标签: c++ class templates type-conversion operator-overloading