我有以下课程:
Automata类
#ifndef Automata_H
#define Automata_H
class Automata {
protected:
// ...
public:
virtual DFA* dfaEquivalent() {}
// ....
};继承自DFA的Automata类
#include "Automata.hpp"
#ifndef DFA_H
#define DFA_H
class DFA : public Automata
{
private:
public:
DFA() {}
};并最终继承了DFA
#include "DFA.hpp"
#ifndef _NFA_H
#define _NFA_H
class NFA : public DFA
{
private:
public:
NFA() { }
DFA* dfaEquivalent()
{}
};
#endif当我有一个NFA实例并想调用dfaEquivalent时,问题就出现了,编译器说:
g++ -c -o main.o main.cpp
In file included from DFA.hpp:1:0,
from NFA.hpp:1,
from Comparador.hpp:5,
from main.cpp:2:
Automata.hpp:96:13: error: ‘DFA’ does not name a type; did you mean ‘DFA_H’?
virtual DFA* dfaEquivalent(){}
^~~
DFA_H
<builtin>: recipe for target 'main.o' failed
make: *** [main.o] Error 1我在继承上犯了什么错误?
发布于 2020-08-24 08:32:15
您在基类(即Automata.h )头中缺少一个前向声明。
编译器不知道什么是DFA类型,它编译Automata.h头(即在Automata类的虚拟函数中)
virtual DFA* dfaEquivalent(){}
// ^^^^--> unknown type由于它是指向DFA类型的指针,所以在Automata.h中为DFA提供一个前向声明,标题将解决这个问题。
#ifndef Automata_H
#define Automata_H
class DFA; // forward declaration
class Automata
{
public:
virtual DFA* dfaEquivalent() {}
// ...code
};
#endif另外,请看一看:When to use virtual destructors?。如果将子类对象存储到指向Automata的指针,则您的Automata可能需要一个。
https://stackoverflow.com/questions/63557316
复制相似问题