The signature of vector::push_back
is:
void push_back (const value_type& val);
which means it is responsible for not corrupting val
.
My function is:
Result User::addFriend(const User* newFriend)
{
// check that newFriend is valid and is not already a friend
if (newFriend == NULL || isFriend(newFriend)) return FAILURE;
friends_.push_back(newFriend);
friendsNum_++;
return SUCCESS;
}
when I compile the .c file I get compilation error:
invalid conversion from 'const User*' to
std::vector User*::value_type
Why do we get this error if push_back promises not to change val?
What is the correct and clean way to overcome the error? maybe by const_cast?
thank you!
User.h:
class User {
...
public:
vector<User*> friends_;
...
}
There is a logical issue with your code. Namely, you are storing pointers to modifiable objects:
vector<User*> friends_;
And yet your addFriend() method takes a pointer to a const object:
Result User::addFriend(const User* newFriend)
// ^^^^^
{
// stuff..
friends_.push_back(newFriend);
}
Those don't line up. As is, push_back
would have to convert your const User*
to a User*
, hence the compile error. One or the other of those types should be changed. Either friends_
needs to be a vector<const User*>
(if you really have no intention of modifying these objects) or addFriend
needs to take a User*
(if you do). Don't use const_cast
!
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments