免责声明:我知道应该避免隐式转换为字符串,并且正确的方法是op<<过载Person.
请考虑以下代码:
#include <string>
#include <ostream>
#include <iostream>
struct NameType {
operator std::string() { return "wobble"; }
};
struct Person {
NameType name;
};
int main() {
std::cout << std::string("bobble");
std::cout << "wibble";
Person p;
std::cout << p.name;
}
Run Code Online (Sandbox Code Playgroud)
prog.cpp: In function ‘int main()’:
prog.cpp:18: error: no match for ‘operator<<’ in ‘std::cout << p.Person::name’
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:112: note: candidates are: std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(std::basic_ostream<_CharT, _Traits>& (*)(std::basic_ostream<_CharT, _Traits>&)) [with _CharT = char, …Run Code Online (Sandbox Code Playgroud) #include <iostream>
struct Int {
int i;
operator int() const noexcept {return i;}
};
int main() {
Int i;
i.i = 1;
std::cout << i;
}
Run Code Online (Sandbox Code Playgroud)
但是,这无法在GCC 4.8.1上编译:
#include <iostream>
#include <string>
struct String {
std::string s;
operator std::string() const {return s;}
};
int main() {
String s;
s.s = "hi";
std::cout << s;
}
Run Code Online (Sandbox Code Playgroud)
以下是错误的相关部分:
错误:'operator <<'不匹配(操作数类型是'std :: ostream {aka std :: basic_ostream}'和'String')
std :: cout << s;SNIP
template std :: basic_ostream <_CharT,_Traits>&std :: …