Congestion overload: public-private search in C ++ class

The following code does not compile, saying β€œerror C2248:β€œ A :: getMe ”: cannot access the private member declared in classβ€œ A. ”Why? I'm trying to call the public interface.

class B
{
};

class A
{
public:
    const B& getMe() const;
private:
    B& getMe(); 
};

int main()
{
A a;
const B& b = a.getMe();
return 0;
}
+3
source share
4 answers

, , , ++. B& A::getMe() main, . , a.getMe() , B& A::getMe() B const& A::getMe() const. a const, . , . private non const member, const , const, non const.

, ​​, : , . , , . .

: , , .

+12

++ . - : , , .

, , const_cast :

const B& b = const_cast<const A&>(a).getMe();

, , , :

const A& const_a = a;
const B& b = const_a.getMe();
+8

a const a.getMe(), , const- .

A const a;
const B& b = a.getMe();

, ( , A).

+4

, const non const a const, non const.

It would not be easier to call the private memeber function something else to avoid confusion in the presence of two functions with the same name but different access.

+3
source

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


All Articles