2014-06-13 77 views
3

C++ 11一個成員變量

什麼迭代,使用基於範圍for循環中,在一個std ::載體,其是類的一個成員的代碼?我我試過以下幾個版本:

struct Thingy { 
    typedef std::vector<int> V; 

    V::iterator begin() { 
     return ids.begin(); 
    } 

    V::iterator end() { 
     return ids.end(); 
    } 

    private: 
     V ids; 
}; 

// This give error in VS2013 
auto t = new Thingy; // std::make_unique() 
for (auto& i: t) { 
    // ... 
} 

// ERROR: error C3312: no callable 'begin' function found for type 'Thingy *' 
// ERROR: error C3312: no callable 'end' function found for type 'Thingy *' 
+2

它適用於普通對象,而不是指針。 – chris

回答

2

tThingy *。您沒有爲Thingy *定義任何功能,您的功能定義爲Thingy

所以,你必須寫:

for (auto &i : *t) 
+0

是的,就是這樣。我想知道爲什麼當t被裸露時,語言不會自動解引用指針。哦,謝謝。 – Dess

+1

我很高興語言不會自動解引用指針! –

+0

@Dess:如果確實如此,那麼參考文獻中就沒有太多要點,會不會有? :P – cHao

0

你應該使用一個 「正常」 的對象,如果你可以:

Thingy t; 
for (auto& i: t) { 
    // ... 
} 

選擇使用std::unique_ptr然後解引用指針:

auto t = std::make_unique<Thingy>(); 
for (auto& i: (*t)) { 
    // ... 
}