开发者

how do i back insert to a vector with a const pointer

hello i have an error with the following code: in my h file i got the following vector:

vecto开发者_运维知识库r<Vehicale*> m_vehicalesVector;

and in my cpp file i got the following function:

void Adjutancy:: AddVehicale(const Vehicale* vehicaleToAdd)
{
    m_vehicalesVector.push_back(vehicaleToAdd);
}

seems like the const Vehicale* vehicaleToAdd is making the problem when i change it to a non const variable it works. thanks in advance.


m_vehicalesVector.push_back() needs Vchicale* as its parameter, while const Vehicale* is given. Compiler denies this because const cannot be removed silently.

Change vector<Vehicale*> m_vehicalesVector to vector<const Vehicale*> m_vehicalesVector can solve this problem.


You can't store a const pointer into a vector of non-const pointers since you could then use the non-const pointer to modify the object pointed to by the const pointer.

You can make it a vector of const pointers:

vector<const Vehicle*> m_vehiclesVector;

or pass in a non-const pointer.

You could also cast away const-ness:

m_vehiclesVector.push_back(const_cast<Vehicle *>(vehicleToAdd));

but I would strongly discourage that approach.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜