c++ - 在对象外部循环遍历 unique_ptr 集合

标签 c++ c++11 unique-ptr

我试图通过让类返回一个 vector::iterator 从类外部循环遍历对象 Baz 内的指针集合。当我运行 for 循环时,出现以下错误:

“const class std::unique_ptr”没有名为“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;
}

最佳答案

你应该首先取消引用你的迭代器:

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

关于c++ - 在对象外部循环遍历 unique_ptr 集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16627735/

相关文章:

c++ - const 指针与指针 : C++

接受任意数量的回调并存储结果的c++类方法

c++ - 如何使用 c++11 std::thread 实现类 QThread 类?

c++11 - 从一种类型到另一种类型的 memcpy。之后我们如何访问目的地?

c++ - 如何在 C++ 列表中保存计时时间

c++ - 为什么在调用 reset() 时,通过 unique_ptr 创建的内存没有被正确删除?

c++ - 读取 fopen 打开的二进制文件 ("ab") (add,binary)

c++ - 如何比较 utf8 字符串,例如 C++ 中的波斯语单词?

c++ - 如何在声明后为 unique_ptr 赋值?

c++ - 如何为 std::unique_ptr 创建一个有效的 C++ 别名模板