C++ 遍历智能指针向量

C++ Iterating through a vector of smart pointers

本文关键字:向量 指针 智能 遍历 C++      更新时间:2023-10-16

我有一个具有这个函数的类:

typedef boost::shared_ptr<PrimShapeBase> sp_PrimShapeBase; 

class Control{
     public:
         //other functions
         RenderVectors(SDL_Surface*destination, sp_PrimShapeBase);
     private:
         //other vars
          vector<sp_PrimShapeBase> LineVector;
};
//the problem of the program
void Control::RenderVectors(SDL_Surface*destination, sp_PrimShapeBase){
    vector<sp_PrimShapeBase>::iterator i;
    //iterate through the vector
    for(i = LineVector.begin(); i != LineVector.end(); i ++ ){
      //access a certain function of the class PrimShapeBase through the smart
      //pointers
      (i)->RenderShape(destination); 
    }
}

编译器告诉我,该类 boost::shared_ptr没有名为"渲染形状"的成员,我觉得很奇怪,因为类 PrimShapeBase 当然具有该函数,但位于不同的头文件中。这是什么原因造成的?

你不是说

(*i)->RenderShape(destination); 

i是迭代器,*ishared_ptr(*i)::operator->()是对象。

那是因为i是一个迭代器。 取消引用它一次会给你智能指针,你需要双重取消引用它。

(**i).RenderShape(destination);

(*i)->RenderShape(destination);