我有以下类:
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
可能需要一个。