考慮以下最小例如:訂單運算符重載決策涉及的臨時
#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;
}
};
但是,這會導致各種含糊之處。
您可能認爲這回答另一個問題爲起點的東西這至少與你想要實現的類似:http://stackoverflow.com/questions/469696/what-is-your-most-useful-cc-snippet/470999#470999你將不得不爲類添加功能接受輸入修飾符(std :: hex,std :: endl ...),但這不應該太難。 – 2010-02-11 16:30:14