const对象 不能调用非const修饰的成员函数

Posted 奥雷连诺

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了const对象 不能调用非const修饰的成员函数相关的知识,希望对你有一定的参考价值。

class 

class UIRect:public RECT
{
public:

    UIRect(LONG leftT = 0, LONG topT = 0, LONG rightT = 0, LONG bottomT = 0)
    {
        left = leftT;
        top = topT;
        right = rightT;
        bottom = bottomT;
    }

    int GetWidth() const 
    {
        return right - left;
    }

    int GetHeight() const
    {
        return bottom - top;
    }


};

  

void DrawRect(const UIRect& rect)
{
    rect.GetWidth();
}

//只有函数右边带了const,才能被const对象使用,否则报编译错误,error C2662: ‘UIRect::GetWidth‘ : cannot convert ‘this‘ pointer from ‘const UIRect‘ to ‘UIRect &‘

const的两个用法

1. const修饰对象不能修改对象,

2. const在成员函数右边表示不能修改成员变量,

这两个是联系在一起的,也就说明const在成员函数右边是不能重载的

 

以上是关于const对象 不能调用非const修饰的成员函数的主要内容,如果未能解决你的问题,请参考以下文章

函数后面的const修饰符的作用

类的const成员

C/C++中各个位置的const关键字

C/C++中各个位置的const关键字

C++面向对象-static、const

const函数