考虑以下最小示例:
#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;
}
};
然而,这会导致各种歧义。