Why put "const" at the end?

Possible duplicates:
C ++ const used in class methods
The value of "const" in the declaration of the C ++ method?

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

This is the declaration overload operator. Why put constin the end? Thanks

+5
source share
5 answers

The keyword constmeans that the method will not modify the object. Since operator==for comparison, nothing needs to be changed. Therefore, this const. It should be omitted for methods such as operator=that DO modify the object.

, , , . http://www.parashift.com/c++-faq-lite/const-correctness.html.

+6

const . - ( ).

, , const , , const, - . , , non-const, , const.

, const ( ), .

:

#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;
}

:

1
0
Press any key to continue . . .
+2

"const" ++ , , .

0
source

He notes that this method is persistent, which means that the compiler will allow you to use the method whenever you have a reference to the corresponding object. If you have a const reference, you can otherwise only refer to methods that are also declared as const.

0
source

A 'const' at the end of the method declaration places this method as safe for invoking a permanent object.

0
source

All Articles