【问题标题】:Overloading of << operator using iterator as a parameter使用迭代器作为参数重载 << 运算符
【发布时间】:2015-06-29 15:23:56
【问题描述】:

我想将枚举值打印为文本并用于重载。假设我有以下代码:

#include <iostream>
#include <map>
#include <string>
#include <vector>
#include <unordered_set>

enum enm{
    One,
    Two
};

class Complex{
public:
friend std::ostream& operator<<(std::ostream& out, std::unordered_multiset<int>::const_iterator i){
    switch (*i){
        case One:{
            return out<<"One";
        }
        case Two:{
            return out << "Two";
        }
    }
}
void func(std::unordered_multiset<int> _v);
};

void Complex:: func(std::unordered_multiset<int> _v){
    _v.insert(One);
    _v.insert(Two);
    for (std::unordered_multiset<int>::const_iterator i(_v.begin()), end(_v.end()); i != end; ++i){
        std::cout <<"Num: " << *i <<std::endl; //need to get here "One", "Two" instead of 0, 1
    }
}

int main(){
    Complex c;
    std::unordered_multiset<int> ms;
    c.func(ms);
    return 0;   
}

问题是这个变体不起作用。所以,我得到 0, 1 而不是 One, Two。不知道如何正确地做到这一点。 谢谢你的帮助!

【问题讨论】:

  • 附带说明:不要使用 _ 作为变量前缀,这是为 c++ 实现内部保留的。

标签: c++ c++11 stl operator-overloading


【解决方案1】:

我假设您将 i 更改为 *i 以便编译您的程序。为了打印迭代器,您必须执行i,但这会失败并出现编译器错误。

问题在于插入运算符在第一次声明时被定义为类中的友元,因此查找该运算符的查找只能依赖于与参数类型关联的命名空间和类,称为 @987654321 的查找@ 或 Koenig 查找。

由于std::ostreamunordered_multiset::const_iterator 未与Complex 关联(请参阅ADL#Details),因此查找无法找到插入运算符。

解决方案是在类之外声明函数,以便操作符的正常unqualified lookup发生:

std::ostream& operator<<(std::ostream&, std::unordered_multiset<int>::const_iterator);
class Complex { .. };

不过,我建议您在类之外定义运算符,因为它似乎不需要访问 Complex 的私​​有/受保护成员(与实体交朋友的目的的一部分) )。

【讨论】:

  • 在类之外声明函数是对部分问题的决定。另一个是--iterator 作为参数,它不是Complex 类的一部分。据我了解,重载函数必须至少采用一个复杂类类型的参数。 Thats why Im 错误地将迭代器作为参数传递。那么,是否有任何变体可以使用重载或不使用重载将枚举值打印为多集中的文本?:)
  • @user3856196 Here's an example that creates a new formatting facet for custom output 。使用os &lt;&lt; print_alpha_num 打开它,使用os &lt;&lt; no_print_alpha_num 关闭它。
猜你喜欢
  • 2011-10-18
  • 2020-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-07
  • 2013-09-07
  • 2017-02-22
  • 2012-03-12
相关资源
最近更新 更多