c++ - 错误:从父类父类派生子类Son时基类未定义

标签 c++ inheritance header-files

我将父级和子级分为两个类,分为.h和.cpp。为什么会出现上述错误?我有另一个解决方案,基本上包含相同的内容,并且没有错误。抱歉,这很琐碎,但是我对c++还是陌生的,并且困惑为什么它在一种解决方案中有效,而在另一种解决方案中无效。

编辑:当我运行该程序时,终端仍会打开并显示父亲的提示行,此后似乎发生了错误。我知道将Son.h包含在父亲中的状态。但是为什么它不能像我写的那样工作呢?我喜欢在cpp文件中包含头文件的想法。

父亲

#pragma once
class Father
{
public:
    Father();
    ~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;
}

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

Son.cpp:
#include "Father.h"
#include "Son.h"
#include <iostream>
using namespace std;

void Son::Talk()
{
    cout << "I'am the son" << endl;
}

Main.cpp:
#include "Son.h"
#include <iostream>
using namespace std;

int main()
{
    Son Bernd;
}

最佳答案

why doesn't it work the way I wrote it?


Son.cpp可以很好地编译,因为它在从Father声明Father.h之前包含了从Son声明Son.h的声明。

该问题发生在Main.cpp中。在这里,您仅包括Son中的Son.h声明。该编译单元不知道Father类。

确保每个 header 都包含所有依赖项并添加
#include "Father.h"

Son.h

关于c++ - 错误:从父类父类派生子类Son时基类未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61848985/

相关文章:

c++ - 在 C++ 和 Fortran 代码之间传递复数数组

c++ - 如何将 socket.async_read_some 的读取处理程序调用同步到特定频率?

java - 如何使类(class)特化有哪些选择或最佳实践?

c - C 中包含头文件

c++ - 与客户共享 C++ DLL 和 H 文件

没有功能头文件的 C++ 程序编译

c++ - 虚拟析构函数必须是公开的吗?

c++ - 检查下一步是否将死

java - 为什么我会收到以下错误以及空构造函数中应该有什么?

c++ - 在模板函数中调用继承的方法