2012-01-29 23 views
0

我試圖在我的類STEntry中超載< <運算符,但仍然遇到此錯誤。我的課上粘貼錯誤。無法在C++中過載輸出流

stentry.h: In function ‘std::ostream& operator<<(std::ostream&, const STEntry&)’: 
stentry.h:48: error: no match for ‘operator<<’ in ‘std::operator<< [with _CharT = char, _Traits = std::char_traits<char>, _Alloc = std::allocator<char>](((std::basic_ostream<char, std::char_traits<char> >&)((std::basic_ostream<char, std::char_traits<char> >*)out)), ((const std::basic_string<char, std::char_traits<char>, std::allocator<char> >&)(& temp->STEntry::lexeme))) << ','’ 
stentry.h:46: note: candidates are: std::ostream& operator<<(std::ostream&, const STEntry&) 

我在STEntry.h中的類。這很簡單。我試圖顯示一些變量值。

#ifndef __STENTRY__ 
#define __STENTRY__ 
#include <string> 

using namespace std; 

class STEntry { 
    public: 
    string lexeme; // addr. of lexema associated with this entry 
    int tokenval; // token value for this entry 
    int offset; // location of variable in block 

    STEntry(string name = "", int newval = 0, int newoffset = 0); 
    // function: constructor ... initializes major fields 

    // Relational operators: 
    bool operator == (const STEntry &) const; 
    bool operator != (const STEntry &) const; 
    friend ostream & operator << (ostream &, const STEntry &); 
}; 

//--- BEGIN IMPLEMENTATION 

//constructor 
STEntry::STEntry(string name, int newval, int newoffset) 
{ 
    lexeme = name; 
    tokenval = newval; 
    offset = newoffset; 
} 

// .... 

//Output a single STEntry to standard output 
std::ostream& operator << (std::ostream& out, const STEntry & temp) 
{ 
    out << temp.lexeme << ',' << temp.tokenval << ',' << temp.offset; 
    return out; 
} 

//--- END OF IMPLEMENTATION 
#endif 

回答

2

你超負荷operator<<就好。這是導致問題的函數內部的一行。

out << temp.lexeme << ',' << temp.tokenval << ',' << temp.offset; 

從錯誤信息,不知道怎麼寫lexeme(一string)到流。

您是否包含<iostream><string>?我只在您的發佈代碼中看到其中的一個。

+0

就是這樣。 TX。 – sri 2012-01-29 02:52:01

1

你可能需要你的頭之前包括的iostream

+0

你的意思是,在ifndefs之前使用include? – sri 2012-01-29 03:43:17

+0

@sri作爲本說你需要包括iostream和字符串 – Chang 2012-02-23 03:32:12

2

添加

#include <iostream> 

到您的文件。

1

您可能沒有在您的項目中包含任何流庫。嘗試#include <iostream><ostream>

0

您實際上必須實施運營商< <換句話說,您必須編寫它。

另外請注意__上的宏名是爲編譯器實現者保留的,不應該使用。

+0

尤其是指'#ifndef __STENTRY__'?好的,謝謝你的建議。 – sri 2012-01-29 03:09:14

+1

如果您有興趣:17.6.4.3.2全局名稱[global.names] 1某些名稱和功能簽名總是保留給實現: - 每個名稱包含雙下劃線_ _或以下劃線開頭後面跟着一個大寫字母 字母(2.12)保留給執行任何用途。 - 以下劃線開頭的每個名稱都保留給實現,以用作全局名稱空間中的名稱。 – 2012-01-29 03:15:49