why put a "const" at the end?

Possible Duplicates:
c++ const use in class methods
Meaning of “const” last in a C++ method declaration?

int operator==(const AAA &rhs) const;

This is a operator overloading declaration. Why put const at the end? Thanks


The const keyword signifies that the method isn't going to change the object. Since operator== is for comparison, nothing needs to be changed. Therefore, it is const . It has to be omitted for methods like operator= that DO modify the object.

It lets the compiler double-check your work to make sure you're not doing anything you're not supposed to be doing. For more information check out http://www.parashift.com/c++-faq-lite/const-correctness.html.


Making a method const will let a contant object of the class to call it. because this method cannot change any of the object's members (compiler error).

It may deserve mention that const is a part of the method's signature, so in the same class you may have two methods of the same prototype but one is const and the other isn't. In this case, if you call the overloaded method from a variable object then the non-const method is called, and if you call it from a constant object then the const method is called.

However, if you have only a const method (there is no non-const overload of it), then it's called from both variable and constant object.

For Example :

#include <iostream>

using std::cout;

class Foo
{
public:
    bool Happy;
    Foo(): Happy(false)
    {
        // nothing
    }
    void Method() const
    {
        // nothing
    }
    void Method()
    {
        Happy = true;
    }
};

int main()
{
    Foo A;
    const Foo B;
    A.Method();
    cout << A.Happy << 'n';
    B.Method();
    cout << B.Happy << 'n';
    return 0;
}

Will output :

1
0
Press any key to continue . . .

任何c ++声明结尾的“const”告诉编译器它不会改变它所属的东西。

链接地址: http://www.djcxy.com/p/40422.html

上一篇: 函数原型中的const参数

下一篇: 为什么要在最后加上一个“const”?