C ++ Создание переменных из защищенного абстрактного / производного класса - PullRequest
0 голосов
/ 25 ноября 2018

Я пытаюсь выяснить, где я ошибаюсь при создании переменных из производного класса.У меня есть абстрактный класс, производный класс, и я пытаюсь создать производный класс в качестве переменной в основной программе тестирования.Однако я получаю ошибку: нет соответствующей функции для вызова DerivedPlayer :: DerivedPlayer () '.Я не смог найти правильный синтаксис для создания и инициализации переменной производного класса.Также обратите внимание, что конструктор абстрактного класса защищен.

Абстрактный заголовок (Base.h)

    #ifndef BASE_H_
    #define BASE_H_

    #include <iostream>
    #include <vector>

    class Base {
      public:
        virtual ~Base() {}

      protected:
        Base(std::string s) : x(0), s(s), v(0) {}

        int x;
        std::string s;
        std::vector<int> v;
    };
    #endif

Производный заголовок (Derived.h)

    #ifndef DERIVED_H_
    #define DERIVED_H_

    #include "Base.h"

    class Derived : public Base {
    public:
        Derived(std::string name){ s = name; }
        virtual ~Derived();
    };

    #endif

Тестовый код(InTest.cpp)

    #include <iostream>
    #include "Derived.h"

    int main() {

        Derived a = Derived("R2-D2");
        Derived b = Derived("C-3PO");

        return 0;
    }

Журнал сборки

    03:23:52 **** Incremental Build of configuration Debug for project InTest ****
    make all 
    Building file: ../src/InTest.cpp
    Invoking: GCC C++ Compiler
    g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/InTest.d" -MT"src/InTest.o" -o "src/InTest.o" "../src/InTest.cpp"
    In file included from ../src/InTest.cpp:2:0:
    ../src/Derived.h: In constructor ‘Derived::Derived(std::string)’:
    ../src/Derived.h:8:27: error: no matching function for call to ‘Base::Base()’
      Derived(std::string name){ s = name; }
                               ^
    ../src/Derived.h:8:27: note: candidates are:
    In file included from ../src/Derived.h:4:0,
                     from ../src/InTest.cpp:2:
    ../src/Base.h:12:2: note: Base::Base(std::string)
      Base(std::string s) : x(0), s(s), v(0) {}
      ^
    ../src/Base.h:12:2: note:   candidate expects 1 argument, 0 provided
    ../src/Base.h:7:7: note: Base::Base(const Base&)
     class Base {
           ^
    ../src/Base.h:7:7: note:   candidate expects 1 argument, 0 provided
    make: *** [src/InTest.o] Error 1

    03:23:52 Build Finished (took 214ms)

1 Ответ

0 голосов
/ 25 ноября 2018

Вот основная часть сообщения об ошибке:

../src/Derived.h: In constructor ‘Derived::Derived(std::string)’:
../src/Derived.h:8:27: error: no matching function for call to ‘Base::Base()’
  Derived(std::string name){ s = name; }

Поскольку Derived наследуется от Base, каждый раз, когда создается объект Derived, конструктор класса Base также должен запускаться,Проблема с вашим текущим кодом состоит в том, что вы позволяете вызывать конструктор Base по умолчанию, но его нет.

Вы решаете его, «вызывая» правильный конструктор Base в Derivedсписок инициализатора конструктора:

Derived::Derived(std::string name)
    : Base(name)
{}
...