Convert const T* const to T*
is it possibile do this kind of cast in C++?
I need to declare my attribute in this way.
Class A {
public:
void update() { ++i_; }
private:
int i_;
}
Class B{
public:
void foo() {
a_->update(); /* Error */
}
private:
const A* const a_;
}
Error is:
passing 'const A' as 'this' argument of 'void A::update()' discards qualifiers [-fpermissive]
I try with static_cast , but is not enough.. does not work.. any ideas?
You have two choices here. Either make A::update a const function-
Class A {
void update() const;
}
or remove the constness of the pointer.
Class B{
public:
void foo() {
const_cast<A*>(a_)->update();
}
private:
const A* const a_;
}
The former would be the preferred method, but that will also stop you from doing anything useful in class A's update.
As a rule of thumb, if you have to cast the const off something then you really want to look at why the pointer is const in the first place.
Using a const member with a non-const method is forbiden (unless using mutable
). Put a const
after declaration of foo()
and update()
:
void update() const { ... }
^^^^^
void foo() const { ... }
^^^^^
or ...
If you don't want to make update
a const
, you can use const_cast
:
void foo() const // Now, this const keyword is optional but recommanded
{
const_cast<A*>(a_)->update();
^^^^^^^^^^^^^^
}
假设你不能将方法声明为const
,并且你知道自己在做什么(tm)以及为什么这样做不好:请尝试const_cast
!
上一篇: 在取消分配任何对象时运行代码