我试图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;
}