为什么const方法可以采用非const引用? [英] Why can a const method take a non const reference?

查看:81
本文介绍了为什么const方法可以采用非const引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道const方法无法修改调用它的对象.看这段代码:

I know a const method cannot modify the object from which it is called. Look at this code:

class A{
    int a;
    public:
        void f(A & a_) const {
        a_.a=5;
        };
};
int main(){
    A x;
    x.f(x);
    return 0;
}

为什么这段代码会编译?在将方法声明为常量时,为什么还要分配对同一类的非const对象的引用?一般来说,编译器如何检查函数可以修改对象的所有可能情况?

Why does this code compile? Why can I even assign a reference to a non const object of the same class, when declaring the method as constant? In general how can the compiler check all the possible situations in which the function could modify the object?

推荐答案

const 成员函数无法使用隐式" this 参数. f(...)(忽略成员可见性)等同于自由功能

A const member function cannot modify the object from which it is called using the "implicit" this parameter. f(...) is (ignoring member visibility) equivalent to the free function

void f(const A* this, A& _a) {
    _a.a = 5;
}

如果传递与非const指针或引用相同的对象,则仍然可以对其进行修改.

If you pass the same object as a non-const pointer or reference, you are still allowed to modify it.

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

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