'operator<<(std :: ostream&,int&)'是不明确的

时间:2017-08-31 12:37:35

标签: c++ operator-overloading

不是这个:

operator<<(std::cout, 0);

与此相同吗?

std::cout<<0;

我尝试了这段代码:

#include<iostream>
int main()
{
    operator<<(std::cout,0);
    return 0;
}

但是我收到以下错误消息:

a.cpp: In function ‘int main()’:
a.cpp:11:28: error: call of overloaded ‘operator<<(std::ostream&, int)’ is ambiguous
a.cpp:11:28: note: candidates are:
/usr/include/c++/4.6/ostream:528:5: note: std::basic_ostream<char, _Traits>& std::operator<<(std::basic_ostream<char, _Traits>&, const unsigned char*) [with _Traits = std::char_traits<char>]
/usr/include/c++/4.6/ostream:523:5: note: std::basic_ostream<char, _Traits>& std::operator<<(std::basic_ostream<char, _Traits>&, const signed char*) [with _Traits = std::char_traits<char>]
/usr/include/c++/4.6/ostream:510:5: note: std::basic_ostream<char, _Traits>& std::operator<<(std::basic_ostream<char, _Traits>&, const char*) [with _Traits = std::char_traits<char>]
/usr/include/c++/4.6/bits/ostream.tcc:323:5: note: std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&, const char*) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/include/c++/4.6/ostream:473:5: note: std::basic_ostream<char, _Traits>& std::operator<<(std::basic_ostream<char, _Traits>&, unsigned char) [with _Traits = std::char_traits<char>]
/usr/include/c++/4.6/ostream:468:5: note: std::basic_ostream<char, _Traits>& std::operator<<(std::basic_ostream<char, _Traits>&, signed char) [with _Traits = std::char_traits<char>]
/usr/include/c++/4.6/ostream:462:5: note: std::basic_ostream<char, _Traits>& std::operator<<(std::basic_ostream<char, _Traits>&, char) [with _Traits = std::char_traits<char>]
/usr/include/c++/4.6/ostream:456:5: note: std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&, char) [with _CharT = char, _Traits = std::char_traits<char>]

有人可以解释一下吗?

1 个答案:

答案 0 :(得分:3)

不,它与:

相同
std::cout.operator<<(0);

使用operator<<(std::cout, 0);启用Argument-Dependent Lookup(ADL),找到多个接受std::basic_ostream<char>int的候选者(或具有有效隐式转换的类型)来自int)作为输入。一旦ADL启动,所有这些各种超载都成为有效的候选者。