无法使用“this” const 成员函数中的指针
我正在经历:有关继承的 C++ 常见问题 和决定实现它只是为了学习它:
#include "Shape.h"
void Shape::print() const
{
float a = this->area(); // area() is pure virtual
...
}
现在,一切(好吧,几乎)都按照常见问题解答中的描述工作,除了 print()
是 const
所以它不能访问 this
指针。一旦你取出const
,它就起作用了。
C++ FAQ 已经存在一段时间了,而且通常都非常好。这是一个错误吗? 是我写错了还是有错别字?如果我错了,我想知道如何在 const
函数中访问 this
指针。
I was going through: C++ FAQs about inheritance and decided to implement it just to learn it:
#include "Shape.h"
void Shape::print() const
{
float a = this->area(); // area() is pure virtual
...
}
Now, everything (well, almost) works as described in the FAQ except that print()
is const
and so it can't access the this
pointer. As soon as you take out const
, it works.
The C++ FAQ has been around for a while and is usually pretty good. Is this a mistake?
Does it have a typo or am I wrong? If I'm wrong, I would like to know how is it possible to access the this
pointer in a const
function.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
问题是area()函数不是const。如果该函数是 const,则可以正常编译。由于您在 const 函数内部,因此 this 指针是 const,因此您只能在其上调用 const 函数。
The problem is that the area() function is not const. If that function was const, then this would compile fine. Since your inside a const function, the this pointer is const and therefore you can only call const functions on it.
为什么无法访问
this
?重点是,只能使用const
成员和方法。因此,如果将Shape::area()
声明为const
,则没有问题。此外,您可以自由读取数据成员值,但不能分配给它们:Why couldn't
this
be accessed? The point is, onlyconst
members and methods can be used. So ifShape::area()
is declaredconst
, there is no problem. Also, you can freely read data member values, but not assign to them:如果
print
被定义为const
,那么它可以使用this
访问const
成员,但不能访问非const 成员:因此当且仅当area
方法声明为时,它可以调用
(即,如果this->area()
>constarea
方法承诺如果调用它,则不会改变其Shape
实例)。If
print
is defined asconst
, then it can usethis
to accessconst
members but not to access non-const members: so it can invokethis->area()
if-and-only-if thearea
method is declared asconst
(i.e. if thearea
method promises that if it's invoked then it won't mutate itsShape
instance).默认情况下将所有函数声明为 const 也是一个好习惯,只有在实际需要修改对象时才不要这样做。这也将有助于发现某些函数修改了不该修改的内容的错误。
It is also a good practice to declare all functions as const by default, and only not do so when you actually need to modify the object. This will also help finding errors of the kind where some function modifies something it is not meant to.
您当然可以访问
this
指针,但在const
函数中,它变成指向const
对象的指针。请记住,this
指针不是真正的指针实例,因此它可以在程序中的不同点更改其类型。You certainly can access the
this
pointer, but in aconst
function it becomes a pointer to aconst
object. Remember, thethis
pointer isn't a real pointer instance, so it can change its type at different points in the program.