我将父级和子级分为两个类,分为.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/