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

问题描述

我有以下课程:

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

我在继承中犯了什么错误

解决方法

您在基类(即Automata.h)标题中缺少前向声明。

编译器当时不知道DFA是什么类型,它编译Automata.h头(即在Automata类的虚函数中)

virtual DFA* dfaEquivalent(){}
//      ^^^^--> unknown type

由于它是指向类型DFA的指针,因此可以在标题DFA中为Automata.h提供前向声明。

#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可能需要一个。