C ++这个指针总是const [英] C++ the this pointer is always const
问题描述
对于类X的非const成员函数,此指针的类型为X * const。
然后,成员函数的这个指针总是const。 / p>
然后,我们总是需要const转换为:
void foo :: p(){
const_cast< int&> (member)= 1;
}
我缺少这里的东西吗?
对于类X的非const成员函数,此指针的类型为X * const。
否,非常量成员函数中的 this
指针的类型只是 X *
(它是一个右值)。但是,即使 都是
X * const
,仍然不会阻止您更改数据成员。
您的代码示例与您的问题不符。它显示了一个const成员函数。在const成员函数中, this
的类型是 const X *
。您不能更改const成员函数内的任何数据成员(除了声明为 mutable
的数据成员除外)。如果你的目标是更改数据成员,那么声明一个成员函数为 const
是一种矛盾。弥补你的心。
For a non const member function of class X, this pointer is of type X* const.
Then, this pointer for a member function is always const.
Then, do we always need to const cast as in:
void foo::p() {
const_cast <int&> (member) = 1;
}
Am I missing something here ?
For a non const member function of class X, this pointer is of type X* const.
No, the type of the this
pointer inside a non-const member function is just X*
(and it is an rvalue). But even if this
were X* const
, that would still not prevent you from changing data members.
Your code example doesn't match your question. It shows a const member function. Inside a const member function, the type of this
is const X*
. You cannot change any data members inside a const member function (with the exception of data members declared as mutable
). It is a contradiction to declare a member function as const
if your goal is to change data members. Make up your mind.
这篇关于C ++这个指针总是const的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!