簡體   English   中英

如何在C ++中使用迭代器進行打印?

[英]how to print using iterator in c++?

我正在用VC ++編寫程序。 在這里,我聲明了Product和Client類。在客戶端中,我使用的是一個函數列表initProduct(),其中list :: iterator i; 使用。我無法使用迭代器顯示列表。 這是我的代碼:

#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");
}

您必須實現以下功能

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的私有屬性。

您需要產生一個ostream& operator<<(ostream& os, const Product& product) ,以打印出您想要顯示的信息。

如果您使用的是C++11 ,則可以使用auto

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

但您必須實現此toString() ,該toString()將顯示您想要的所有信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM