运算符过载问题
Operator overloading problems
>我显然在类定义中有朋友,为了更清楚,删除了实现代码等......
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 );
您已经定义了一个需要stringstream&
的operator>>
和Ref const&
,因此内部调用有效。 而你的 operator>>
返回一个stringstream&
,即 std::istream
,因此可以调用函数operator>>( std::istream&,
unsigned char )
。 其中:
ss >> i >> r;
是
operator>>( operator>>( ss, i ), r );
内部调用返回一个std::istream&
,并且没有超载operator>>
std::istream&, Ref const&
.
如上所述:超载>>
应始终采取 std::istream&
作为第一个参数,并返回一个 std::istream&
.
ss >> i >> r; <------- why do I get an error here?
您忘记告诉我们错误是什么,或者发布给您错误的实际代码。当我修复已发布代码中的明显错误时,我得到:
cannot bind ‘std::basic_istream<char>’ lvalue to ‘std::basic_istream<char>&&’
第一个问题是ss >> i
不会调用您的重载;您不能为内置类型(如 uint8_t
)重载流运算符。因此,这将调用标准库定义的重载,该重载返回对istream
的引用,而不是stringstream
。 您的运算符需要对 stringstream
的引用,因此第二个运算符将失败。
您应该遵循约定并使用通用ostream
而不是特定stringstream
:
friend std::istream& operator>>(std::istream& s, const Ref& r) { return s; }
如果你真的希望运算符做任何有用的事情,那么你需要从第二个参数中删除const
。
- 一个关于在C++中重载布尔运算符的问题
- 使用运算符 [] 引用 std::vector 上最后一个元素时出现问题<>
- 运算符继承和 cpp 核心准则 c.128 的问题
- 在C++中使用重载提取运算符时出现问题
- 移动赋值运算符;尝试引用已删除的函数.我该如何解决这个问题?
- 关于条件块的问题与&&运算符有关
- 重载运算符与添加问题
- 加、乘、除、减复数的问题 C++ - 运算符重载
- 我需要这方面的帮助C++在使用逻辑运算符时是/否问题
- 0xC0000005:访问冲突读取位置 0x00000000. 重载 == 运算符的问题
- 如何解决不明确的运算符过载问题?
- 屏幕插入运算符<<的运算符过载问题
- 如何通过使用 2 位或更多数字的 XOR 运算符来执行此操作C++问题
- 在 C++ 的自定义运算符中删除与删除[](不同于常见的删除与删除[]问题)
- 用户定义的文本运算符(在原始模式下)存在问题
- 关于重载 -> 运算符中 const 关键字的特定位置的问题
- 字符 * 未从重载运算符或内存管理问题正确返回
- constexpr 运算符重载使用参数的问题
- c++中重载输入运算符的问题
- 有趣的问题运算符重载