2013-05-18 47 views
3

我試圖通過讓類返回vector::iterator來從類外部遍歷對象Baz中的指針集合。當我運行for環路我得到以下錯誤:在對象之外循環遍歷unique_ptr集合

'const class std::unique_ptr' has no member named 'getName'

有人能解釋這是怎麼回事,我該如何通過內部巴茲的唯一指針集合管理循環?提前致謝。

#include <iostream> 
#include <string> 
#include <memory> 
#include <vector> 

class BaseInterface 
{ 
protected: 

std::string Name; 

public: 

virtual ~BaseInterface(){} 
virtual void setName(std::string ObjName) = 0; 
virtual std::string getName() = 0; 
}; 

class Foo : public BaseInterface 
{ 
public: 

void setName(std::string ObjName) 
{ 
    Name = ObjName; 
} 

std::string getName() 
{ 
    return Name; 
} 

}; 

class Bar : public BaseInterface 
{ 
public: 

void setName(std::string ObjName) 
{ 
    Name = ObjName; 
} 

std::string getName() 
{ 
    return Name; 
} 

}; 

class Baz 
{ 
    protected: 

    std::vector< std::unique_ptr<BaseInterface> > PointerList; 

    public: 

    void push_back(std::unique_ptr<BaseInterface> Object) 
    { 
     PointerList.push_back(std::move(Object)); 
    } 

    std::vector< std::unique_ptr<BaseInterface> >::const_iterator begin() 
    { 
     return PointerList.begin(); 
    } 

    std::vector< std::unique_ptr<BaseInterface> >::const_iterator end() 
    { 
     return PointerList.end(); 
    } 

}; 

int main(int argc, char ** argv) 
{ 

std::unique_ptr<BaseInterface> FooObj(new Foo()); 
FooObj->setName("Foo"); 

std::unique_ptr<BaseInterface> BarObj(new Bar()); 
BarObj->setName("Bar"); 

std::unique_ptr<Baz> BazObj(new Baz()); 

BazObj->push_back(std::move(FooObj)); 
BazObj->push_back(std::move(BarObj)); 

for(auto it = BazObj->begin(); it != BazObj->end(); ++it) 
{ 
    std::cout << "This object's name is " << it->getName() << std::endl; 
} 

return 0; 
} 

回答

3

你應該先提領你的迭代器:

std::cout << "This object's name is " << (*it)->getName() << std::endl; 
//          ^^^^^ 
+0

我想*這很好,但我想我忘記了括號。感謝您指出我的錯誤。 – Tek

+0

@Tek:很高興幫助 –

+0

一個小的跟進,但我認爲' - >'會解除引用'它已經。這有時讓我很困惑,因爲有時候只需要一個'*'。 – Tek