C ++从受保护的抽象/派生类创建变量

时间:2018-11-25 10:45:43

标签: c++ inheritance abstract-class derived-class

我试图找出在派生类中创建变量的地方。我有抽象类,派生类,并试图在主测试程序中将派生类创建为变量。但是我得到了一个错误:没有匹配的函数可以调用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 :(得分:1)

这是错误消息的主要部分:

../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)
{}