2012-03-29 67 views
0

這是我的測試程序。變量s1包含一個包含用戶定義類型的對象的向量。我想過載運算符來很好地打印這個向量,每行一個元素。如何從覆蓋運算符遍歷矢量數據成員<<

#include <iostream> 
#include "myclasses.h" 
using namespace std; 

int main() { 

    myclass s1; 

    s1.add_point(7000, 10); 
    s1.add_point(8000, 11); 
    s1.add_point(9000, 12); 

    cout << s1 << endl; 

    return 0; 

} 

這是類定義。基本上它只是一組其他用戶定義的對象。我希望< <操作員可以打印所有條目,每行一個。假設「另一類」具有所需的支持方法。

class myclass { 
    vector<anotherclass> ps; 
public: 
    void add_point(double, double); 
    friend ostream &operator<<(ostream &out, const myclass &s); 
}; 

void myclass::add_point(double first, double second) { 
    ps.push_back(anotherclass(first, second)); 
} 

ostream &operator<<(ostream &out, const myclass &s) { 
    vector<anotherclass>::iterator itr; 
    vector<anotherclass> psp=s.ps; // Why do I need this? Why can't I use s.ps.begin() and s.ps.end() in the for loop directly? 
    for (itr=psp.begin() ; itr != psp.end() ; ++itr) { 
     cout << "(" << itr->get_first() << "," << itr->get_second() << endl; 
    } 
    return out; 
} 

我已經評論了一行,我需要添加才能讓它在我的程序中工作。我不知道爲什麼這條線是必要的。有人可以向我解釋嗎?

回答

4

iterator成員類型始終允許您修改引用的對象。因此,您不能從const &參數(例如s)獲得iterator。您需要聲明局部變量的類型爲vector<anotherclass>::const_iterator。每個集裝箱類別都有一個const_iteratoriterator平行。

單線修補程序工作的原因是新構建的vector不是const,與它構建的函數參數不同。

在C++ 11中,您可以使用auto itr = s.ps.begin()而不是任何名稱的迭代器類型。或者只使用for (auto const &obj : s.ps)並完全放棄迭代器。

+0

太棒了!我有兩本關於C++的書,包括Bjarne的「原理與實踐」。這兩本書都沒有提到這一點。 (Bjarne的書在附錄B的表格中提到了一個不斷重複的迭代器)。感謝您的其他提示。 – 2012-03-29 04:17:12

1

我的猜測是因爲你聲明s爲const,所以不允許訪問它的迭代器。 當你使用矢量psp = s.ps時,你的程序基本上將s.ps複製到一個新的可修改的矢量psp中。