【发布时间】:2022-01-11 11:33:55
【问题描述】:
我正在处理多个类和文件,因此我创建了这个虚拟代码来更好地定义我的问题。我有一个父类Parent 和一个子类Child。我已将这两个文件分别放在一个 .h 和一个 .cpp 文件中
parent.h
class Parent
{
Parent(int a, int b, int c);
protected:
void somefunc();
};
parent.cpp
#include<iostream>
#include "parent.h"
Parent::Parent(int a, int b, int c)
{
std::cout<<"Answer is: "<<a+b+c;
}
void Parent::somefunc()
{
std::cout << "I am some func";
}
child.h
#include "parent.h"
class Child : public Parent
{
public:
void funk();
};
child.cpp
#include"child.h"
void Child::funk()
{
somefunc();
}
我正在使用另一个文件 running.cpp 来运行它。
#include "child.h"
int main()
{
Child a;
a.funk();
return 0;
}
尝试使用 g++ 构建它,给了我错误:
running.cpp: In function ‘int main()’:
running.cpp:4:11: error: use of deleted function ‘Child::Child()’
Child a;
^
In file included from running.cpp:1:0:
child.h:2:7: note: ‘Child::Child()’ is implicitly deleted because the default definition would be ill-formed:
class Child : public Parent
^~~~~
child.h:2:7: error: no matching function for call to ‘Parent::Parent()’
In file included from child.h:1:0,
from running.cpp:1:
parent.h:3:5: note: candidate: Parent::Parent(int, int, int)
Parent(int a, int b, int c);
^~~~~~
parent.h:3:5: note: candidate expects 3 arguments, 0 provided
parent.h:1:7: note: candidate: constexpr Parent::Parent(const Parent&)
class Parent
^~~~~~
parent.h:1:7: note: candidate expects 1 argument, 0 provided
parent.h:1:7: note: candidate: constexpr Parent::Parent(Parent&&)
parent.h:1:7: note: candidate expects 1 argument, 0 provided
我使用的 g++ 命令是g++ *.cpp -o test
我知道我应该以某种方式提供参数来运行 Parent 的构造函数,但我不知道该怎么做。
- 如何消除此错误?
- 如果错误与此无关,当子类继承其构造函数中具有参数的类时,如何创建子类的对象?我还需要调用参数构造函数,所以我不能只创建另一个空白构造函数并使用它。
【问题讨论】:
-
你声明了
Child构造函数,但是你在哪里定义(实现)它? -
错误告诉你声明了
Child::Child()但你没有实现它。 -
感谢您的关注,我正在自己测试一些东西,但在发布之前没有正确恢复。编辑了问题!
-
还是一样的问题,只是上移了一步:你声明了
Parent默认构造函数,但是你从来没有定义(实现)它。 -
仍然是那个基本错误。再次改变
标签: c++ class oop inheritance g++