C++ Iterating through a vector of smart pointers

我的未来我决定 提交于 2019-12-03 17:20:33

问题


i have a class that has this function:

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); 

    }
}

The compiler tells me that the class boost::shared_ptr has no member called 'RenderShape' which I find bizarre since the class PrimShapeBase certainly has that function but is in a different header file. What is the cause of this?


回答1:


Don't you mean

(*i)->RenderShape(destination); 

?

i is the iterator, *i is the shared_ptr, (*i)::operator->() is the object.




回答2:


That's because i is an iterator. Dereferencing it once gives you the smart pointer, you need to double dereference it.

(**i).RenderShape(destination);

or

(*i)->RenderShape(destination); 


来源:https://stackoverflow.com/questions/11960631/c-iterating-through-a-vector-of-smart-pointers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!