The*_*der 0 c++ operator-overloading
我明确地在类定义中有朋友并且使它更清楚,删除了实现代码等...
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.
}
};
Run Code Online (Sandbox Code Playgroud)
你为什么超载std::stringstream?你应该总是超载std::istream或std::ostream
(取决于方向).std::stringstream甚至可以使用(std::istringstream或者
std::ostringstream通常更合适),这是非常罕见的,
即使它们是,operator>>通常会返回a std::istream&,而不是a std::stringstream&.
编辑:
关于为什么一个似乎工作:
ss >> r >> i;
Run Code Online (Sandbox Code Playgroud)
是
operator>>( operator>>( ss, r ), i );
Run Code Online (Sandbox Code Playgroud)
你已经定义了一个operator>>取a stringstream&
和Ref const&,所以内部调用是有效的.而你的
operator>>回报stringstream&,其中ISA
std::istream,这样的功能operator>>( std::istream&,
unsigned char )可以被调用.在哪里:
ss >> i >> r;
Run Code Online (Sandbox Code Playgroud)
是
operator>>( operator>>( ss, i ), r );
Run Code Online (Sandbox Code Playgroud)
内部调用返回的std::istream&,并没有超载operator>>的std::istream&, Ref const&.
超载:如上所述>>应该总是拿
std::istream&,因为第一个参数,并返回
std::istream&.
| 归档时间: |
|
| 查看次数: |
197 次 |
| 最近记录: |