命名空间中的ostream运算符<<隐藏了其他ostream ::运算符
这个问题在这里已经有了答案:
  如此处所述,这是一个名称隐藏的例子。  通过在命名空间MyNamespace定义operator<< ,所有来自较高命名空间(如全局)的定义都被隐藏起来。 
请注意,如此处所述:
  此功能不会干扰Koenig lookup [...],因此仍然会找到来自std:: IO运算符。 
(有关Koenig查找的详细信息)
  解决方法是using指令引用其他名称空间中的重载,如此处和此处所述。  Michael Nastenko在评论中提到了这一点。 
  因此using ::operator<<;  , ::表示全局名称空间。 
因此代码将变为:
#include <string>
#include <iostream>
typedef std::pair<std::string, std::string> StringPair;
std::ostream& operator<<(std::ostream& os, const StringPair &pair) {
    os << pair.first << '.' << pair.second;
    return os;
}
namespace MyNamespace {
    class MyClass {};
    using ::operator<<;
    std::ostream& operator<< (std::ostream&, const MyClass &);
    void xxx();
}
void MyNamespace::xxx() {
    StringPair pair("1","2");
    std::cout<<pair<<std::endl;
}
int main() {
    MyNamespace::xxx();
    return 0;
}
例如Coliru
链接地址: http://www.djcxy.com/p/73073.html上一篇: ostream operator << in Namespace hides other ostream::operator
下一篇: std::atomic error: no ‘operator++(int)’ declared for postfix ‘++’ [
