c++ - 实现流操作符时编译错误

标签 c++ stl stream operators shadowing

我正在尝试为继承 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/

相关文章:

c# - 流式传输到包中,打包到 WordDocument 中,然后再返回

node.js - Node : How can I use pipe and change one file from a multipart

c++ - "Use of undeclared identifier"- 代码有什么问题?

c++ - 使用 std::function 时选择自动返回类型而不是构造函数的调用运算符

c++ - 如何制作 LPCWSTR 的拷贝?

c++ - std::vector 的引用

c++ - 保留 vector 是线程安全的吗?

c++ - 虚拟继承中派生类的大小

c++ - 使用字符数组作为映射中的键

python - 通过 Python 进行音频/视频广播