2012-06-15 44 views
1

这里是困扰我:重载运算符<<在C++中没有发现

QTextStream& operator << (QTextStream& a, FAPPDebug& b); 

和实施FAPPDebug.cpp:

在头文件FAPPDebug.h比如我有一个重载的 operator <<
QTextStream& operator << (QTextStream& a, FAPPDebug& b) 
{ 
    QString msg = *b.stream->ts.string(); // just take the message from b 
    a << msg; 
    return a; 
} 

和相应的函数调用:

QTextStream(stdout) << (debug() << "Quitting because application object is not set."); 

不论如何怪异,这看起来,T他使用MSVC2010在Windows下编译(和工作!)

debug()只是一个宏,用于从当前位置创建FAPPDebug对象。请注意额外的()周围(调试()< <“...”),而不是它没有产生我想要的。

在Linux下的另一端与G ++ 4.4,我得到以下错误:

MessageBroker.cpp:91: error: no match for ‘operator<<’ in ‘QTextStream(stdout, QFlags((QIODevice::OpenModeFlag)3u)) << ((FAPPDebug*)((FAPPDebug*)FAPPDebug(417, ((const char*)"MessageBroker.cpp"), ((const char*)(& PRETTY_FUNCTION)), (LogLevel)7u).FAPPDebug::operator<<(((const char*)"Module")))->FAPPDebug::operator<<(((const QString&)((const QString*)(& ModuleBase::getModuleDescription()())))))->FAPPDebug::operator<<(((const char*)"Quitting because application object is not set."))’ /usr/local/Trolltech/Qt-4.8.2/include/QtCore/qtextstream.h:184: note: candidates are: FAPPDebug.h:94: note: QTextStream& operator<<(QTextStream&, FAPPDebug&)

(有很多候选人,我只是不停什么是重要的)

我已经修改了函数调用是:

::operator << (QTextStream(stdout), debug() << "Failed to schedule application startup."); 

,我得到的错误信息:

MessageBroker.cpp: In member function ‘bool MessageBroker::init(Application*, const QString&)’: MessageBroker.cpp:91: error: no matching function for call to ‘operator<<(QTextStream, FAPPDebug&)’ /usr/local/Trolltech/Qt-4.8.2/include/QtCore/qchar.h:396: note: candidates are: QDataStream& operator<<(QDataStream&, const QChar&) /home/ferenc/work/trunk/Core/Common/FAPPDebug.h:94: note:
QTextStream& operator<<(QTextStream&, FAPPDebug&)

因此,您可以看到每次都找到正确的函数(是的,FAPPDebug.h头文件包含在MessageBroker.cpp中),但“更符合标准的”编译器无法使用它。我有这种感觉,这是我在某个地方对标准的理解上的一个小故障,所以我请求你帮忙找到它。

编辑:操作者在class FAPPDebug

EDIT2声明为朋友:调试()是一个宏,并且被定义,如:

#define debug() FAPPDebug(__LINE__, __FILE__, __PRETTY_FUNCTION__, LOG_DEBUG) 

即它只是创建了一个带有指示当前位置的参数的FAPPDebug对象。

谢谢! f。

回答

1

我认为问题可能是您的插入操作符接受引用(左值)作为第一个参数,如预期的那样,但您尝试传递从构造函数自动创建的右值。想想看,你如何期望一个自动创建的QTextStream(stdout)能够生成一个类型的调用序列,QTextStream(stdout)< < a < < b < < c。实际上,这是x < < a然后x < < b然后x < < c。为了生活在一个句子中发生,我认为第一个和返回都必须是常量引用,它能够引脚您的右值。 或者你也可以声明一个像QTextStream qout(stdout)这样的变量,然后使用qout。

1

不应该是您的operator<<的第二个参数是FAPPDebug const&?即使某些编译器仍然无法检测到错误,您也无法使用临时文件初始化非const引用,即 。

+0

在这种情况下,它找到了'FAPPDebug.h:94:注意:QTextStream&operator <<(QTextStream&,const FAPPDebug&)'函数,但仍然没有建立连接 – fritzone

+0

什么是'调试()'?除非它是对'QTextStream'的非const引用,否则不能调用你的函数。使用'const',右侧操作数可以是临时的(包括隐式转换的结果)。 –

1

如果仔细看看,编译器看到的函数和你定义的函数是不一样的。

它看到什么:

no matching function for call to ‘operator<<(QTextStream, ... 

什么它定义

QTextStream& operator<<(QTextStream&, ... 

这似乎是临时对象不能作为非const引用传递。 因此,要么将其更改为QTextStream const&或使用右值参考

编辑:哦,好吧,我只是明白,作为第一个参数传递流不能真的是const。如果可能的话,使用右值引用或只是通过值捕获,在我看来,现在是唯一的方法。这是你造成问题的(debug() ...)对象。