2014-06-13 79 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)) { 
    // ... 
}