Kompilator nie może znaleźć odpowiedniego przeciążenia funkcji [duplikat]

Dec 11 2020

Mam małą klasę bazową, która definiuje 3 przeciążenia dla funkcji. Przeciążenie A wywołuje przeciążenie B, które jest czysto wirtualne, a jego implementacja w klasie pochodnej wywołuje przeciążenie C.

Mój pełny kod wygląda następująco:

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;
}

Ten kod daje błędy:

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

Dlaczego kompilator dwukrotnie nie znajduje poprawnego przeciążenia? (raz w wywołaniu przeciążenia C w klasie pochodnej i raz podczas wywoływania przeciążenia A w głównym)

Odpowiedzi

2 super Dec 11 2020 at 12:42

Jeśli zadeklarujesz funkcję w klasie pochodnej o tej samej nazwie co w klasie bazowej, deklaracja w klasie pochodnej będzie cieniała funkcje w klasie bazowej.

Tak więc Derivedjedyny widoczny funcjest ten (int, int).

Jednym prostym sposobem rozwiązania tego problemu jest ściągnięcie funkcji klasy bazowej do zestawu przeciążeń za pomocą 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);
};