我正在经历:关于继承的C++常见问题并决定实现它(只是为了学习它)
#include "Shape.h"
void Shape::print() const
{
float a = this->area(); // area() is pure virtual
...
}
Run Code Online (Sandbox Code Playgroud)
现在,一切(好吧,差不多)按照项目:faq:23.1中的描述工作,除了print()是const,所以它不能访问"this"指针,一旦取出const,它就可以工作.现在,C++常见问题解答已经存在了一段时间,通常都很好.这是一个错误吗?他们有错字还是错了?如果我错了,我想知道如何在const函数中访问"this"指针.
为什么无法this访问?关键是,只能使用const成员和方法.所以,如果Shape::area()宣布const,没有问题.此外,您可以自由读取数据成员值,但不能分配给它们:
class Shape
{
int i;
void print() const;
virtual float area() const = 0;
virtual void modify() = 0;
};
void Shape::print() const
{
float a = this->area(); // call to const member - fine
int j = this->i; // reading const member - fine
this->modify(); // call to non const member - error
this->i++; // assigning to member - error
}
Run Code Online (Sandbox Code Playgroud)