我试图通过让类返回Baz
来从类外部的对象vector::iterator
内循环遍历指针集合。当我运行for
循环时,我收到以下错误:
'const class std::unique_ptr' has no member named 'getName'
有人可以解释发生了什么以及如何设法循环遍历baz中的唯一指针集合吗?提前谢谢。
#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;
}
答案 0 :(得分:3)
您应首先取消引用迭代器:
std::cout << "This object's name is " << (*it)->getName() << std::endl;
// ^^^^^