2013-03-16 125 views
1

我正在開發gsoap web服務,我正在檢索查詢的對象向量。我有兩種方法來實現它:首先通過簡單循環和迭代器。他們都沒有工作。std :: cout中'operator <<'不匹配

的錯誤是:

error: no match for 'operator<<' in 'std::cout mPer.MultiplePersons::info.std::vector<_Tp, _Alloc>::at<PersonInfo, std::allocator<PersonInfo> >(((std::vector<PersonInfo>::size_type)i))'

MultiplePersons mPer; // Multiple Person is a class, containing vector<PersonInfo> info 
std::vector<PersonInfo>info; // PersonInfo is class having attributes Name, sex, etc. 
std::vector<PersonInfo>::iterator it; 

cout << "First Name: \t"; 
cin >> firstname; 
if (p.idenGetFirstName(firstname, &mPer) == SOAP_OK) { 
    // for (int i = 0; i < mPer.info.size(); i++) { 
    // cout << mPer.info.at(i); //Error 
    //} 
    for (it = info.begin(); it != info.end(); ++it) { 
     cout << *it; // Error 
    } 

} else p.soap_stream_fault(std::cerr); 

} 

很明顯,運營商cout超載operator<<的問題。我已經看到了與此有關的幾個問題,但沒有人幫助我。如果有人能提供一個具體的例子來解決這個問題,那將非常感激。 (請不要一概而論,我是C++的新手,我花了三天時間尋找解決方案。)

+0

@Baum mit Augen,2013年3月16日提出這個問題,你說它已經有一個答案(2014年3月23日提出)。而不是標記其他問題重複,你標記了這一個。無法理解你的邏輯。 – Kahn 2017-03-06 12:12:40

+0

在清理舊的常見問題時,詢問時間不再是主要標準。相反,Q/A的有用性是關鍵。我選擇了另一個,因爲它有一個實際的MCVE,所以答案更簡潔,因爲它們不需要首先提供一個示例類體。我覺得這對未來的訪問者來說更容易閱讀。 – 2017-03-06 13:01:42

回答

6

您需要爲PersonInfo提供輸出流運算符。是這樣的:

struct PersonInfo 
{ 
    int age; 
    std::string name; 
}; 

#include <iostream> 
std::ostream& operator<<(std::ostream& o, const PersonInfo& p) 
{ 
    return o << p.name << " " << p.age; 
} 

此運算符允許類型A << B,其中Astd::ostream實例(其中std::cout是其中之一)和B的表達式是一個PersonInfo實例。

這允許你做的做這樣的事情:

#include <iostream> 
#include <fstream> 
int main() 
{ 
    PersonInfo p = ....; 
    std::cout << p << std::endl; // prints name and age to stdout 

    // std::ofstream is also an std::ostream, 
    // so we can write PersonInfos to a file 
    std::ofstream person_file("persons.txt"); 
    person_file << p << std::endl; 
} 

從而允許您打印解除引用的迭代器。

+0

如何在循環內引用std :: ostream&oprator <<()? – Kahn 2013-03-16 13:23:14

+0

@你好,你已經做了,這裏'cout << * it;'。這就是我在談論「A << B」的部分中要解釋的內容。 – juanchopanza 2013-03-16 13:30:08

+0

但我仍然得到相同的錯誤。 – Kahn 2013-03-16 13:31:28

1

*it的結果是PersonInfo類型的L值。編譯器抱怨沒有operator<<,它採用PersonInfo類型的右側參數。

的代碼工作,你需要提供這樣的運營商,比如像這樣:

std::ostream& operator<< (std::ostream &str, const PersonInfo &p) 
{ 
    str << "Name: " << p.name << "\nAge: " << p.age << '\n'; 
    return str; 
} 

運營商的具體實現要看你的需求爲代表,當然在輸出的類別。

+0

我創建了它,但錯誤是一樣的。與運算符不匹配<< – Kahn 2013-03-16 13:30:44

+0

@Hesper是否可以從調用它的函數中看到運算符聲明? – Angew 2013-03-16 13:36:34

+0

你可以看看這段代碼嗎? http://jsfiddle.net/yZps8/ – Kahn 2013-03-16 13:40:21

0

它告訴你的是,沒有一個已知的途徑(控制檯輸出)*它的內容。

it是一個迭代器 - 可以把它像一個列表

名單是info所以*是在info當前項目,這是PersonInfo項目列表的指針。

因此cout << *it;表示輸出到控制檯當前引用的PersonInfo

但是,錯誤消息告訴你編譯器不知道PersonInfo應該如何呈現給控制檯。

你需要做的就是創建一個名爲操作是<<接受一個對象cout是(ostream)和PersonInfo對象,然後將PersonInfo的各個位寫入cout

+0

我創建了std :: ostream&operator <<(std :: ostream&o,const PersonInfo&p)並實現了它。但是,我仍然遇到同樣的錯誤。 – Kahn 2013-03-16 13:29:04

相關問題