• 카테고리

    질문 & 답변
  • 세부 분야

    프로그래밍 언어

  • 해결 여부

    미해결

[16:00]함수가 const인지 아닌지로 overloading을 하는 게 맞나요? +코드 오류 질문

22.08.28 18:39 작성 조회수 164

0

#include <iostream>

#include <string>

using namespace std;

class Some {

public:

string _val = "default";

const string& getVal() const {

cout << "const version" << endl;

return _val;

}

string& getVal() {

cout << "non-const version" << endl;

return _val;

}

};

int main() {

Some some;

some.getVal();

const Some some2;

some2.getVal();

return 0;

}

[질문 1]

some.getVal()과 some2.getVal()같이 오버로딩이 가능한 것이,

함수가 const인지 아닌지로 구분을 했기 때문인지

아니면 return type이 const인지 아닌지로 구분을 했기 때문인지 궁금합니다.

[질문 2]

return type으로는 오버로딩을 할 수 없기 때문에 질문 1의 답은 전자라고 추측하고 확인을 하기 위해 코드를 아래와 같이 바꿔 봤습니다.(7번째 줄을 const string& getVal() const에서 string& getVal() const 로 바꿔 본 것밖에 없습니다.)

#include <iostream>

#include <string>

using namespace std;

class Some {

public:

string _val = "default";

string& getVal() const {

cout << "const version" << endl;

return _val;

}

string& getVal() {

cout << "non-const version" << endl;

return _val;

}

};

int main() {

Some some;

some.getVal();

const Some some2;

some2.getVal();

return 0;

}

다음과 같이 바꿨을 때 string& getVal() const cout << "const version" << endl;

return _val;

}

의 return _val부분에서 'qualifiers dropped in binding reference of type "std::strung &" to initialer of type "const std::string" '이라는 오류가 났습니다.

오류의 원인이 궁금합니다.

답변 1

답변을 작성해보세요.

0

강민철님의 프로필

강민철

2022.08.30

[질문 1]

some.getVal()과 some2.getVal()같이 오버로딩이 가능한 것이,

함수가 const인지 아닌지로 구분을 했기 때문인지

아니면 return type이 const인지 아닌지로 구분을 했기 때문인지 궁금합니다.

>> 전자가 맞습니다.

가령 아래의 코드는 잘 컴파일 됩니다.

#include <iostream>
using namespace std;

class Test {
protected:
    int x;

public:
    Test(int i)
        : x(i)
    {
    }
    void fun() const
    {
        cout << "fun() const called " << endl;
    }
    void fun() { cout << "fun() called " << endl; }
};

int main()
{
    Test t1(10);
    const Test t2(20);
    t1.fun();
    t2.fun();
    return 0;
}

[질문 2]

첨부하신 코드에 대한 오류 이유

>> const 를 사용하는 이유는 해당 함수가 속해있는 클래스의 멤버변수를 바꾸지 않기 위함입니다.

그런데 멤버변수 레퍼런스를 리턴해버리면 변경이 가능해집니다. 그래서 발생한 오류입니다.

요컨대 아래 코드는 error가 없습니다.

#include <iostream>
#include <string>

using namespace std;
class Some {
  public:
    string _val = "default";

  string getVal() const {
    cout << "const version" << endl;
    return _val;
  }

  string & getVal() {
    cout << "non-const version" << endl;
    return _val;
  }
};

int main() {
  Some some;
  some.getVal();
  const Some some2;
  some2.getVal();
  return 0;
}