错误:基类在从基类父派生类 Son 时未定义

Error: base class undefined in deriving class Son from baseclass Father

本文关键字:基类 Son 派生 未定义 错误      更新时间:2023-10-16

我做了两个类父子,分为.h和.cpp。为什么我会收到上述错误?我有另一个解决方案,包含基本相同且没有错误。抱歉,如果这是微不足道的,但我是 c++ 的新手,并且对为什么它在一个解决方案中有效而不适用于另一个解决方案感到困惑。

编辑:当我运行程序时,终端仍然打开并显示父亲的cout线,之后似乎发生了错误。我知道将父.h包括在儿子里面的souts。但是为什么它不能按照我写的方式工作呢?我喜欢在 cpp 文件中包含头文件的想法。

父亲·

#pragma once
class Father
{
public:
Father();
~Father();
};

父亲.cpp:

#include "Father.h"
#include <iostream>
using namespace std;
Father::Father()
{
cout << "I am the father constructor" << endl;
}
Father::~Father()
{
cout << "I am the father deconstructor" << endl;
}

儿子:

#pragma once
class Son : public Father
{
public:
void Talk();
};

儿子.cpp:

#include "Father.h"
#include "Son.h"
#include <iostream>
using namespace std;
void Son::Talk()
{
cout << "I'am the son" << endl;
}

主.cpp:

#include "Son.h"
#include <iostream>
using namespace std;
int main()
{
Son Bernd;
}

为什么它不能按照我写的方式工作?

Son.cpp编译得很好,因为它包括Father.hFather声明,然后再声明Son来自Son.h

Main.cpp中出现问题。在这里,您仅包括来自Son.hSon声明。此编译单元不知道类Father

确保每个标头都包含其所有依赖项并添加

#include "Father.h"

Son.h.