【问题标题】:Why operator<< does not implicitly converting my custome class object to string为什么 operator<< 不会将我的自定义类对象隐式转换为字符串
【发布时间】:2020-12-16 23:43:35
【问题描述】:

我有一个类实现了公共string 转换成员函数。当与 operator&lt;&lt;(iostream &amp;, xxx) 结合使用时,我期望我的类会自动(隐式)转换为 string 从而适合参数类型。

然而,事实并非如此。为什么,我不想写operation&lt;&lt; 函数。

#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&lt;&lt; 采用 std::string(或者,准确地说,std::basic_string)是一个模板。模板参数推导过程中不考虑隐式转换。

标签: c++ class templates type-conversion operator-overloading


【解决方案1】:

operator&lt;&lt; for std::string 是模板,template argument deduction 不会考虑隐式转换,会失败。

类型推导不考虑隐式转换(除了上面列出的类型调整):这是overload resolution 的工作,稍后会发生。

正如您所展示的,您可以将A 显式转换为std::string,或者为A 编写operator&lt;&lt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-09
    • 2013-06-16
    • 1970-01-01
    • 1970-01-01
    • 2017-04-09
    相关资源
    最近更新 更多