2013-07-03 46 views
0

我正在用VC++寫一個程序。在這裏,我聲明類產品和客戶端。在客戶端我使用函數列表initProduct()在列表:: iterator我;我使用迭代器無法顯示列表。 這是我的代碼:如何在C++中使用迭代器打印?

#include "StdAfx.h" 
#include <iostream> 
#include <string> 
#include <list> 
#include <iterator> 
using namespace std; 
class Product 
{ 
    int item_code; 
    string name; 
    float price; 
    int count; 
     public: 
    void get_detail() 
    { 
     cout<<"Enter the details(code,name,price,count)\n"<<endl; 
     cin>>item_code>>name>>price>>count; 
    } 

}; 

class Client 
{ 
public: 

    list<Product> initProduct() 
    { 
     char ans='y'; 
     list<Product>l; 
     list<Product>::iterator i; 
     while(ans=='y') 
     { 
      Product *p = new Product(); 
      p->get_detail(); 
      l.push_back(*p); 
      cout<<"wanna continue(y/n)"<<endl; 
      cin>>ans; 
     } 
     cout<<"*******"<<endl; 

     for(i=l.begin(); i!=l.end(); i++) 
      cout << *i << ' '; //ERROR no operator << match these operand 
     return l; 
    } 
}; 
int main() 
{ 
    Client c; 
    c.initProduct(); 
    system("PAUSE"); 
} 
+0

它不會工作,因爲您正試圖''輸出'Product'類型的操作數。你不能''所有的東西'。<< <<'操作數沒有你剛創建的類型的實現。我不知道你真的想要打印什麼。 –

+0

不要在堆上創建'Product',然後將其複製到'list'中,因爲堆中的副本正在泄漏內存。 – rwols

回答

2

你需要產生ostream& operator<<(ostream& os, const Product& product),打印要顯示的信息。

0

如果您使用C++11您可以使用auto

for(auto it : Product) 
    { 
     cout << it.toString(); 
    } 

但你必須要實現這個toString()這將顯示所有你想要

3

您必須實現以下功能的相關信息

class Product { 
// ... 
    friend std::ostream& operator << (std::ostream& output, const Product& product) 
    { 
     // Just an example of what you can output 
     output << product.item_code << ' ' << product.name << ' '; 
     output << product.price << ' ' << product.count; 
     return output; 
    } 
// ... 
}; 

您聲明函數是類的一個朋友,因爲它必須能夠訪問私有屬性的Product