我有一个 ostream 的子类,用来定义格式化缓冲区。有时候我想要创建一个临时对象,并立即使用通常的 << 运算符将一个字符串插入到它中间,像这样:
M2Stream() << "the string";
很不幸,程序调用了operator<<(ostream, void *)成员重载,而不是operator<<(ostream, const char *)非成员重载。
我编写了下面的示例作为测试,在其中定义了自己的M2Stream类以重现问题。
我认为问题在于M2Stream()表达式产生了一个临时变量,这会导致编译器更喜欢void *重载。但是为什么呢?如果我将非成员重载的第一个参数设置为const M2Stream&,则出现歧义。
另一个奇怪的事情是,如果我首先定义一个const char *类型的变量,然后再调用它,而不是使用字面char字符串,它就会调用所需的const char *重载,如下所示:
const char *s = "char string variable";
M2Stream() << s;
好像字面字符串的类型与const char*变量不同!它们不应该是相同的类型吗?为什么编译器在我使用临时字符字符串和字面字符字符串时会调用void*重载函数?
#include "stdafx.h"
#include <iostream>
using namespace std;
class M2Stream
{
public:
M2Stream &operator<<(void *vp)
{
cout << "M2Stream bad operator<<(void *) called with " << (const char *) vp << endl;
return *this;
}
};
/* If I make first arg const M2Stream &os, I get
\tests\t_stream_insertion_op\t_stream_insertion_op.cpp(39) : error C2666: 'M2Stream::operator <<' : 2 overloads have similar conversions
\tests\t_stream_insertion_op\t_stream_insertion_op.cpp(13): could be 'M2Stream &M2Stream::operator <<(void *)'
\tests\t_stream_insertion_op\t_stream_insertion_op.cpp(20): or 'const M2Stream &operator <<(const M2Stream &,const char *)'
while trying to match the argument list '(M2Stream, const char [45])'
note: qualification adjustment (const/volatile) may be causing the ambiguity
*/
const M2Stream & operator<<(M2Stream &os, const char *val)
{
cout << "M2Stream good operator<<(const char *) called with " << val << endl;
return os;
}
int main(int argc, char argv[])
{
// This line calls void * overload, outputs: M2Stream bad operator<<(void *) called with literal char string on constructed temporary
M2Stream() << "literal char string on constructed temporary";
const char *s = "char string variable";
// This line calls the const char * overload, and outputs: M2Stream good operator<<(const char *) called with char string variable
M2Stream() << s;
// This line calls the const char * overload, and outputs: M2Stream good operator<<(const char *) called with literal char string on prebuilt object
M2Stream m;
m << "literal char string on prebuilt object";
return 0;
}
输出:
M2Stream bad operator<<(void *) called with literal char string on constructed temporary
M2Stream good operator<<(const char *) called with char string variable
M2Stream good operator<<(const char *) called with literal char string on prebuilt object