我正在尝试为继承 std::basic_iostream<char>
的流类实现流提取运算符.
不幸的是,我遇到了我并不真正理解的编译错误。
这是我简化的(非功能性)代码:
#include <iostream>
class MyWhateverClass {
public:
int bla;
char blup;
};
class MyBuffer : public std::basic_streambuf<char> {
};
class MyStream : public std::basic_iostream<char> {
MyBuffer myBuffer;
public:
MyStream() : std::basic_iostream<char>(&myBuffer) {}
std::basic_iostream<char>& operator >> (MyWhateverClass& val) {
*this >> val.bla;
*this >> val.blup;
return *this;
}
};
int main()
{
MyStream s;
s << 1;
int i;
s >> i;
return 0;
}
我遇到了两个类似的错误:
C2678 binary '>>': no operator found which takes a left-hand operand of type 'MyStream'
,一个在我实现运算符的行中,一个在我从流中获取 int 的行中。
有趣的是,当我删除运算符实现时,这两个错误都消失了。
谁能告诉我这里发生了什么?
最佳答案
我已经解决了这个问题。你得到编译错误的原因是阴影。您的 MyStream::operator>>(MyWhateverClass&)
隐藏所有版本的 std::basic_iostream::operator>>
。为了解决此问题,您需要使用 using declaration :
class MyStream : public std::basic_iostream<char> {
MyBuffer myBuffer;
public:
MyStream() : std::basic_iostream<char>(&myBuffer) {}
using std::basic_iostream<char>::operator>>;
std::basic_iostream<char>& operator >> (MyWhateverClass& val) {
*this >> val.bla;
*this >> val.blup;
return *this;
}
};
附言最初的答案完全错误,无需保存)
关于c++ - 实现流操作符时编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47616579/