c++ - 试图通过重载打印对象的 vector ?

标签 c++ vector iterator hashtable overloading

我正在研究涉及线性探测的哈希表程序。我试图打印出 Symbol 类对象的 vector ,但每次我尝试这样做时都会遇到两个错误。我在下面发布了这些错误:

LinearProbing.h: In instantiation of 'void HashTable<HashedObj>::print() [with HashedObj = Symbol]':
Driver.cpp:79:21:   required from here
LinearProbing.h:82:4: error: cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue to 'std::basic_ostream<char>&&'
In file included from /opt/local/include/gcc47/c++/iostream:40:0,
                 from Driver.cpp:1:
/opt/local/include/gcc47/c++/ostream:600:5: error:   initializing argument 1 of 'std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char; _Traits = std::char_traits<char>; _Tp = HashTable<Symbol>::HashEntry]'

这是我尝试在 HashTable 类中打印 vector 的地方...

class HashTable
{
    ///...
    void print()
    {
        typename vector<HashEntry>::iterator vIter = array.begin;
        while(vIter != array.end())
        {
            cout<< *vIter << "\n";
            ++vIter;
        }
    }

    private:
        vector<HashEntry> array;
};

还有我在 Symbol 类中的重载...

friend ostream & operator <<(ostream & outstream, Symbol & symbol) //overloaded to print out the the HashTable
{
    int num = symbol.type;
    string name = symbol.data;
    outstream << name << " : " << num << "\n";
    return outstream;
}

最佳答案

不确定您在那里做什么,但您已经定义了一个 HashEntry vector 并在 HashEntry 上调用了 cout,但是您的 operator<< 重载却在 Symbol 上运行。

类 Symbol 的运算符<<应该看起来像这样

class Symbol {
    private:
        friend ostream& operator<<(ostream &os, const Symbol &s);

        int type;
        string data;


};

ostream& operator<<(ostream &os, const Symbol &s)
{
    os << s.data << " : " << s.type;
    return os;
}

关于c++ - 试图通过重载打印对象的 vector ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22505882/

相关文章:

c++ - 带有子类容器的子类的非标准迭代器

c++ - std::function:无法将派生类参数转换为基类参数

c++ - C++ 语言中的构造函数

c++ - 避免在 c++ vector 或 valarray 中初始化

c++ - 存储STL列表迭代器的指针安全吗?

python - 分解高度分支的解析器的大多数 pythonic 方法

c++ - 算法只绘制相机看到的内容?

c++ - 在缓冲区之间移动字节时出现意外结果

c++ - 用方括号 [] 初始化 std::vector<int> ;怎么了?

vector - Julia .重新标记向量