我的测试.cpp文件使用的是默认运算符<<;这个签名有什么问题?
My test.cpp file is using a default operator<<; What's wrong with this signature?
我花了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++;
}
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 静态数据成员的问题-修复链接错误会导致编译器错误
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 请解释这句话(cout<<1+int((a<b)^((b-a)&1) )<<endl
- 一个关于在C++中重载布尔运算符的问题
- 首要问题的答案让值班员搞错了
- setlocale的C++土耳其字符串问题
- 如何重构类层次结构以避免菱形问题
- 呼叫运营商<<临时
- 基于boost的程序的静态链接——zlib问题