繁体   English   中英

C ++为什么当我从const方法内部的ref成员调用non const方法时,我没有得到编译错误

[英]c++ why I do not get compile error when I call non const method from ref member inside const method

为什么我可以从const方法内部的ref成员调用non const方法? 我希望得到编译错误,例如如果m_a不是引用类型。 http://cpp.sh/上运行

// Example program
#include <iostream>

class A
{
    public:
    void nonConstMethodOfA()
    {
        std::cout << "nonConstMethodOfA is called" << "!\n";
    }
};

class B
{
    public:
    B(A& a)
    : m_a(a)
    {
        constMethodOfB();
    }

    private:
    A& m_a;
    void constMethodOfB() const
    {
        m_a.nonConstMethodOfA();
    }
};

int main()
{
  A varA;
  B varB(varA);
}

const A &表示“对const A的引用”

A &表示“对可变A的引用”

引用不能重新分配,因此A &也隐式表示“对可变A的const引用”。

const成员函数意味着你this将指向const对象,因而this->fn()只能被称为如果fn()是常量。 它不会锁定类型,也不会锁定任何类似类型的输入参数或全局变量。 但是,您也可以根据需要将其指定为const。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM