为什么我可以从const方法中调用非const成员函数指针? [英] Why can I call a non-const member function pointer from a const method?

查看:50
本文介绍了为什么我可以从const方法中调用非const成员函数指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一位同事询问了一些这样的代码,这些代码最初包含模板.

A co-worker asked about some code like this that originally had templates in it.

我已经删除了模板,但是核心问题仍然存在:为什么这样编译就可以了?

I have removed the templates, but the core question remains: why does this compile OK?

#include <iostream>

class X
{
public:
     void foo() { std::cout << "Here\n"; }
};

typedef void (X::*XFUNC)() ;

class CX
{
public:
    explicit CX(X& t, XFUNC xF) : object(t), F(xF) {}      
    void execute() const { (object.*F)(); }
private:
    X& object;
    XFUNC F;
}; 

int main(int argc, char* argv[])
{   
    X x; 
    const CX cx(x,&X::foo);
    cx.execute();
    return 0;
}

鉴于CX是const对象,并且其成员函数 execute 是const,因此在CX :: execute中, this 指针是const.

Given that CX is a const object, and its member function execute is const, therefore inside CX::execute the this pointer is const.

但是我可以通过成员函数指针来调用非常量成员函数.

But I am able to call a non-const member function through a member function pointer.

成员函数是否在世界的常识中指出了文件化的漏洞?

Are member function pointers a documented hole in the const-ness of the world?

我们错过了哪些(可能对其他人显而易见)的问题?

What (presumably obvious to others) issue have we missed?

推荐答案

在这种情况下, object 是对 X 引用对const X 引用. const 限定符将应用于成员(即引用,但引用不能为 const ),而不是引用的对象.

In this context object is a reference to a X, not a reference to a const X. The const qualifier would be applied to the member (i.e. the reference, but references can't be const), not to the referenced object.

如果您将类定义更改为不使用引用:

If you change your class definition to not using a reference:

// ...
private:
    X object;
// ...

您得到了预期的错误.

这篇关于为什么我可以从const方法中调用非const成员函数指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆