【发布时间】:2021-01-26 08:23:01
【问题描述】:
考虑下面的struct,它有一个用户定义的转换函数,可以将自己转换为const char*;
struct S {
operator const char*() { return "hello"; }
};
与<iostream>一起工作,我们可以打印struct S而没有错误消息:
std::cout << S{} << '\n';
但是如果我将返回类型更改为std::string:
struct S {
operator std::string() { return "hello"; }
};
我收到此编译器错误消息:
<source>:11:13: error: no match for 'operator<<' (operand types are 'std::ostream' {aka 'std::basic_ostream<char>'} and 'S')
11 | std::cout << S{} << '\n';
| ~~~~~~~~~ ^~ ~~~
| | |
| | S
| std::ostream {aka std::basic_ostream<char>}
<source>:11:18: note: 'S' is not derived from 'const std::__cxx11::basic_string<_CharT, _Traits, _Allocator>'
11 | std::cout << S{} << '\n';
| ^
为什么编译器不能使用std::string 转换?内置和类类型的转换函数有区别吗?
【问题讨论】:
标签: c++ iostream cout stdstring