2012-06-15 61 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() ...)對象。