【发布时间】:2019-04-27 05:55:17
【问题描述】:
我试图找出从派生类创建变量的问题所在。我有抽象类,派生类,并试图在主测试程序中创建派生类作为变量。但是我得到了错误:没有匹配的函数调用 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)
【问题讨论】:
-
请复制粘贴你得到的full和complete错误输出。
-
完整的错误已发布在 OP 中,并且是:../src/Derived.h:8:27: 错误:没有匹配函数调用“Base::Base()”。整个编译日志太大,无法作为评论发布。
-
您应该在问题正文中发布完整的错误(包括信息说明等)。请编辑您的问题。请尝试创建一个minimal reproducible example 向我们展示,因为您展示的代码不应使用
DerivedPlayer默认构造函数,因此您展示的错误消息与您当前展示的代码不符。 -
已修改代码,包含构建日志。
-
我在这里没有看到抽象类。你打算有一个抽象类吗?
标签: c++ inheritance abstract-class derived-class