我看到的代码片段如下:如何在const成员函数中调用“delete this;”?
class UPNumber {
public:
UPNumber();
UPNumber(int initValue);
...
// pseudo-destructor (a const member function, because
// even const objects may be destroyed)
void destroy() const { delete this; } // why this line is correct???
...
private:
~UPNumber();
};
首先,我相信上面的类定义是正确的。 这是我的问题,为什么我们可以像上面那样定义函数'destroy'? 被问到的原因是,我们为什么可以在const成员函数中修改'this'?
@詹姆斯,在这里,我们不能称之为“删除upn”b/c析构函数是私有的。 - thx – q0987 2011-02-28 23:34:50
@ q0987:班级成员可以访问私人会员。因为'delete this'表达式,函数'destroy'需要访问析构函数,并且因为它是类的成员而具有访问权限。 – GManNickG 2011-02-28 23:51:26
@GMan:我认为OP在抱怨我的例子,它最初使用'UPNumber'类而不是'int'。 – 2011-02-28 23:54:00