컴파일러가 올바른 함수 오버로드를 찾지 못함 [중복]

Dec 11 2020

함수에 대해 3 개의 오버로드를 정의하는 작은 기본 클래스가 있습니다. 오버로드 A는 순수 가상 인 오버로드 B를 호출하고 파생 클래스에서의 구현은 오버로드 C를 호출합니다.

내 완전한 코드는 다음과 같습니다.

struct Base {
        int func(int a) {return func(a, a+1);}
        int func(int a, int b, int c) {return a+b+c;}
        virtual int func(int a, int b)=0;
};

struct Derived : public Base {
        int func(int a, int b);
};

int Derived::func(int a, int b) {
        return func(a,b,a+b);
}

int main(int argc, char* argv[]) {
        Derived d;
        d.func(1);
        return 0;
}

이 코드는 오류를 생성합니다.

test.cpp: In member function ‘virtual int Derived::func(int, int)’:
test.cpp:12:21: error: no matching function for call to ‘Derived::func(int&, int&, int)’
   12 |  return func(a,b,a+b);
      |                     ^
test.cpp:11:5: note: candidate: ‘virtual int Derived::func(int, int)’
   11 | int Derived::func(int a, int b) {
      |     ^~~~~~~
test.cpp:11:5: note:   candidate expects 2 arguments, 3 provided
test.cpp: In function ‘int main(int, char**)’:
test.cpp:17:10: error: no matching function for call to ‘Derived::func(int)’
   17 |  d.func(1);
      |          ^
test.cpp:11:5: note: candidate: ‘virtual int Derived::func(int, int)’
   11 | int Derived::func(int a, int b) {
      |     ^~~~~~~
test.cpp:11:5: note:   candidate expects 2 arguments, 1 provided

컴파일러가 올바른 오버로드를 두 번 찾지 못하는 이유는 무엇입니까? (파생 클래스에서 C를 오버로드하기위한 호출에서 한 번, 메인에서 오버로드 A를 호출 할 때 한 번)

답변

2 super Dec 11 2020 at 12:42

기본 클래스와 동일한 이름을 가진 파생 클래스에서 함수를 선언하면 파생 클래스의 선언이 기본 클래스의 함수를 섀도 잉합니다.

따라서에서 Derived유일한 표시 func(int, int)하나입니다.

이를 해결하는 쉬운 방법 중 하나는 기본 클래스 함수를 using.

struct Derived : public Base {
        using Base::func; // All the func overloads are now pulled into Derived's scope
        int func(int a, int b);
};