显然我在类定义中有 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::istream
或 std::ostream
上重载
(取决于方向)。这是极其罕见的
std::stringstream
甚至会被使用(std::istringstream
或
std::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/