2014-09-25 212 views
-3

我有一個類和該類的元素向量。我需要在我的矢量的特定位置插入新對象,但我甚至無法訪問我想要的位置。我試圖打印我的迭代器,但它不工作......我測試了一個int整數的迭代器,它工作正常,我不能使它與我自己的類一起工作......我錯過了什麼?訪問vector的迭代器<myClass>

ToDo individualTask; 
vector<ToDo> myToDoList; 
vector<ToDo>::iterator it; 

myToDoList.push_back(individualTask); 
cout << myToDoList.size() << endl; 

myToDoList.resize(10); 

for (it = myToDoList.begin(); it != myToDoList.end(); ++it) { 
    cout << *it << endl; // not working 
} 

我試過*它 - > toString()和它說,我的課沒有toString方法

+0

您需要爲您創造類的toString它不存在默認情況下(不像Java或C#)相同的運營商<<。如果你從你的編譯器粘貼了確切的錯誤信息,這將有所幫助。 – Borgleader 2014-09-25 21:14:29

+0

你可以'cout'一個'ToDo'對象嗎?另外,'resize'可能會使迭代器失效。 – juanchopanza 2014-09-25 21:14:44

+0

什麼是「待辦事項」? – 101010 2014-09-25 21:16:52

回答

1

你的代碼是不工作的原因是,你的迭代器指向(A什麼ToDo對象)沒有定義輸出操作符。

如果要使用operator<<()打印出ToDo對象,則需要爲您的類定義一個對象。

這裏是一個粗略的例子給你的想法:

#include <string> 
#include <ctime> 
#include <iostream> 

// Example ToDo class 
class ToDo 
{ 
    // declare friend to allow << to access your private members 
    friend std::ostream& operator<<(std::ostream& os, const ToDo& todo); 
private: 
    std::time_t when; // unix time 
    std::string what; // task description 

public: 
    ToDo(std::time_t when, const std::string& what): when(when), what(what) {} 
    // etc... 
}; 

// This should go in a .cpp file. It defines how to print 
// Your ToDo class objects 
std::ostream& operator<<(std::ostream& os, const ToDo& todo) 
{ 
    // todo.when needs formatting into a human readable form 
    // using library functions 
    os << "{" << todo.when << ", " << todo.what << "}"; 
    return os; 
} 

// Now you should be able to output ToDo class objects with `<<`: 

int main() 
{ 
    ToDo todo(std::time(0), "Some stuff"); 

    std::cout << todo << '\n'; 
}