Inflearn Community Q&A
질문이요
Written on
·
883
0
class A
{
private:
int value;
public:
int& getValue() const
{ return value;}
};
getValue()함수 리턴타입을 레퍼런스로 했더니
return value; 이부분에
int& 형식에서 const int 형식 이니셜라이저로의
바인딩 참조에서 한정자가 삭제되었습니다
라고 나오는데 왜 이러는 건가요?
C++
Answer 1
4
int main()
{
A a;
int &b = a.getValue();
b = 3;
return 0;
}
const member function은 const object에 사용하도록 되어있습니다.
작성하신 것과 같이 const가 아닌 reference를 return 하게되면 위와 같은 방법으로 value의 값을 바꿀 수 있는데, 이러한 가능성을 아예 막아놓은 것입니다.
https://www.learncpp.com/cpp-tutorial/810-const-class-objects-and-member-functions/
https://stackoverflow.com/questions/30146562/error-qualifiers-dropped-in-binding-reference-of-type-x-to-initializer-of-type
읽어보시면 도움이 될 것 같네요.





