Afficher un message
Vieux 01/07/2008, 16h57   #3
Eric Pruneau
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Use const_cast to modify member variable?


"Immortal Nephi" <Immortal_Nephi@satx.rr.com> a écrit dans le message de
news: 1db02a01-0b82-4fb7-b701-ca2a5b183f8a...oglegroups.com...
> How can I modify member variable inside class if member function has
> const like mem_Func(void) const. Please do not offer the keyword --
> mutable. I want to know if keyword -- const_cast can be done.
>
> If mutable is only the solution, I will follow not to use const_cast.


Ok it is Evil but you can do it.

struct EvilClass
{
void EvilFunct() const;
int _a;
};

void EvilClass::EvilFunct() const
{
int& tmp = const_cast<int&>(_a);
tmp = 5; // now _a == 5
}


You can also define a template function if you have many variables like
that.

struct EvilClass
{
void EvilFunct() const;

template<typename T>
void EvilSet(T const& val, T const& NewVal) const;

int _a;
};

void EvilClass::EvilFunct() const
{
EvilSet(_a, 5); // much cleaner but maybe also much evil
}

template<typename T>
void EvilClass::EvilSet(T const& val, T const& NewVal) const
{
T& tmp = const_cast<T&>(val);
tmp = NewVal;
}

------------------------

Eric Pruneau


  Réponse avec citation
 
Page generated in 0,04788 seconds with 9 queries