考虑以下最简示例:
#include <iostream>
using namespace std;
class myostream : public ostream {
public:
myostream(ostream const &other) :
ostream(other.rdbuf())
{ }
};
int main() {
cout << "hello world" << endl;
myostream s(cout);
s << "hello world" << endl;
myostream(cout) << "hello world" << endl;
}
输出结果在g++和Visual C++上均为:
hello world
hello world
0x4012a4
看起来,将内容写入临时对象myostream(cout)
的版本似乎更喜欢成员运算符 ostream::operator<<(void *)
,而不是自由运算符 operator<<(ostream &, char*)
。这似乎取决于对象是否有名称。
为什么会这样?我如何防止这种行为发生?
编辑: 为什么会发生已经在各种答案中清楚了。至于如何预防这种情况,以下方法似乎可行:
class myostream : public ostream {
public:
// ...
myostream &operator<<(char const *str) {
std::operator<<(*this, str);
return *this;
}
};
然而,这会导致各种模糊性。