为什么此对象检测不到父类?



我有以下类:

Automata

#ifndef Automata_H
#define Automata_H
class Automata {
protected:
// ...
public:
virtual DFA* dfaEquivalent() {}
// ....
};

Automata继承的DFA

#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

我在继承方面犯了什么错误?

基类(即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

顺便说一下:什么时候使用虚拟析构函数?。如果将子类对象存储为指向Automata的指针,则Automata可能需要一个。

最新更新