What is all invalid with const functions?

class A{
private:
    int a;
public:
    A() {a = 4;}
    const int& random1() const {return a; }
    //int&     random2() const {return a; }
    const int* random3() const {return &a;}
    //int*     random4() const {return &a;}
};

int main(){
    A objA;
    cout<<objA.random1()<<"\n";
    cout<<*objA.random3()<<"\n";
}

random2()and random4()not permitted, as defined above. I somehow knew this all the time, but I never came across this when I wrote my own code, until today.

That everything except these two cases is unacceptable in constant functions?

Any reference to standard C ++ text would also be helpful. Thank!

+3
source share
2 answers

First make sure that there const T*is a pointer to some Tthat cannot be changed. The second thing to remember is access to all elements through this->.

So (§9.3.1):

- ​​const, volatile const volatile. cvqualifiers (9.3.2).

(§9.3.2):

(9.3) - this -lvalue, , . X X *. - ​​const, - const X *, - ​​, X *, - ​​const volatile, const X *.

A const this const T*.

: int& a this->a, this - const T*, a const int. const int int&. .

, const, const , , const.

+10

-- -const--, . const, , this - .

0

Source: https://habr.com/ru/post/1756460/


All Articles