c++ - 运算符重载问题

标签 c++ operator-overloading

显然我在类定义中有 friend ,为了更清楚,删除了实现代码等...

class Ref
{
    public:
        Ref(char* s, size_t l) : _s(s), _l(l) {}
    private:
        char* _s;
        size_t _l;
};

class foo
{
    public:
        friend stringstream& operator>>(std::stringstream& s, uint8_t& v) { return s; }
        friend stringstream& operator>>(std::stringstream& s, const Ref& r) { return s; }
    private:
        std::stringstream ss;
        void example(void)
        {
            char b[256];
            Ref r(b, sizeof(b));
            uint8_t i;

            ss >> i >> r;    <------ Why do I get an error here?
            ss >> r >> i;    <------ But this one seems to compile fine.
        }
};

最佳答案

为什么要在 std::stringstream 上重载?你应该 总是在 std::istreamstd::ostream 上重载 (取决于方向)。这是极其罕见的 std::stringstream 甚至会被使用(std::istringstreamstd::ostringstream 通常更合适),并且 即使它们是,operator>> 通常也会返回 std::istream&,而不是 std::stringstream&

编辑:

关于为什么看起来有效:

ss >> r >> i;

operator>>( operator>>( ss, r ), i );

您已经定义了一个operator>>,它接受一个stringstream&Ref const&,所以内部调用是有效的。和你的 operator>> 返回一个stringstream&是A std::istream,所以函数operator>>( std::istream&, unsigned char ) 可以调用。作为:

ss >> i >> r;

operator>>( operator>>( ss, i ), r );

内部调用返回一个std::istream&,并没有 为 std::istream&, Ref const& 重载了 operator>>

如上所述:重载的 >>> 应该总是 std::istream& 作为第一个参数,并返回一个 std::istream&

关于c++ - 运算符重载问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19096163/

相关文章:

c++ - 这是 gcc 中 std::valarray 实现的错误吗?

C++ 问题重载运算符 - 类分配

c++ - undefined reference : dll -> free function -> overloaded operator -> templated struct

myClass(x,y,z) = value 的 C++ 运算符重载

c++ - 关于C中的任务递归(Visual Studio 15)

c++ - 是否有可能调用 WriteFile 并且应用程序将永远等待回调?

c++ - 为什么删除的移动语义会导致 std::vector 出现问题?

c++ - 完全删除 vector C++

c++ - 如何支持 Variant 类型的隐式转换,例如从 int 到 unsigned long?

c++ - 部分模板特化的下标运算符重载