【问题标题】:Why this object doesn't detect the father class?为什么这个对象没有检测到父类?
【发布时间】:2020-12-12 20:58:39
【问题描述】:

我有以下课程:

Automata

#ifndef Automata_H
#define Automata_H

class Automata {

protected:
   // ...
public:
   virtual DFA* dfaEquivalent() {}
   // ....
};

继承自AutomataDFA

#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

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

【问题讨论】:

  • AutomataDFA 一无所知。为什么要返回DFA* 而不是Automata*
  • 旁注:不要在标题保护之外包含文件。将它们包含在里面。

标签: c++ class oop inheritance virtual-functions


【解决方案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

作为旁注,请查看:When to use virtual destructors?。如果您将子类对象存储为指向Automata 的指针,您的Automata 可能需要一个。

【讨论】:

    猜你喜欢
    • 2021-02-10
    • 2010-10-25
    • 1970-01-01
    • 2017-11-05
    • 2019-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多