我的测试.cpp文件使用的是默认运算符<<;这个签名有什么问题?



我花了30分钟想弄清楚这是什么问题:

From .h file:

// H/T sent. d-linked list Set
#ifndef SET_H
#define SET_H
#include <iostream>
#include <string>
using namespace std;
typedef string ELEMENT_TYPE;  // a set for string elements
class Set{
private:
    struct Elem {
        ELEMENT_TYPE info;
        Elem *prev, *next;
    };
    Elem *_head, *_tail;
    int _size;
    void copyCode(const Set & v);
    void destructCode();
    ostream& dump(ostream& out, const Set &v);
public:
    Set();
    Set(const Set &rhs);
    ~Set();
    Set& operator=(const Set &rhs);
    bool insert(ELEMENT_TYPE);
    bool erase(ELEMENT_TYPE);
    void clear();
    int size() const { return _size; }
    bool find(ELEMENT_TYPE) const;
    class Iterator{
    private:
    Elem * _cur;
    public:
        Iterator(){}
        explicit Iterator( Elem* );
    Iterator operator++( int );
    Iterator operator++();
        Iterator operator--( int);
    Iterator operator--();
    bool operator==( const Iterator& rhs );
    bool operator!=( const Iterator& rhs );
    ELEMENT_TYPE& operator*();
    ostream& operator<< ( ostream& );
    };
    Iterator begin() const; 
    Iterator end() const; 
    friend ostream& operator<< (ostream&, Set&);
};
bool operator==(const Set&, const Set&);
bool operator!=(const Set&, const Set&);
Set operator&(const Set&, const Set&);
Set operator|(const Set&, const Set&);
#endif

From .cpp file:

string& Set::Iterator::operator*(){
    return _cur -> info;
}

ostream& Set::Iterator::operator<< ( ostream& os ){
    os << _cur -> info << "n";
    return os;
}
从test.cpp:

Set s1;
s1.insert( "1" );
s1.insert( "2" );
s1.insert( "3" );
cout << "Hin";
Set::Iterator it = s1.begin();
while( it != s1.end() ){
    cout << *it;
    it++;
}
cout << "Byen";

对我来说,这看起来很好,就像每个操作符<<但是,当我运行我的test.cpp文件时,我把我的代码通过它的步伐,我得到:

Hi
321Bye

这显然不是我在运算符<<中提供的信息定义,我也试过用一个假输出代替访问值,比如"hin";但收效甚微。这让我相信我错误地定义了它,它使用了一些通用的字符串输出操作符。

我相信这是一个非常简单的问题,但我没有第二只眼睛很容易接近。

编辑:有些人评论说代码是完美的(脸红),问题是无法解决的,但我不知道我错过了什么,所以我包括了完整的头文件。由于明显的空间原因,我没有包括.cpp。如果你认为问题可能在某个领域,我会很高兴地发布我的定义。

问题是输出不包含换行符,这表明根本没有使用操作符。为什么操作符没有正确重载它(感谢JBently)

谢谢!

不能实现operator<<作为类的方法,它必须是一个全局函数!

你的操作符<<根本不起作用,因为在方法实现中总是首先隐含参数是这个,所以你的实现类似于具有以下签名的函数:

ostream& operator<< (this, ostream& );

但要使运算符<<工作-第一个参数应该是ostream&实现operator作为全局函数,您的问题将得到解决:

ostream& operator<< ( ostream& str, iterator& iter );

在这部分代码中,您只需对迭代器解引用(调用operator*)

Set::Iterator it = s1.begin();
while( it != s1.end() ){
    cout << *it;
    it++;
}

如果需要调用operator<<重写:

Set::Iterator it = s1.begin();
while( it != s1.end() ){
    cout << it;
    it++;
}

相关内容

最新更新