尚未宣布枚举

Enum has not been declared?

本文关键字:枚举 布枚举      更新时间:2023-10-16

我会遇到此错误。就像编译器无法识别我的声明

 g++ -c main.cc
In file included from Storage.h:7:0,
                 from Server.h:5,
                 from Control.h:8,
                 from main.cc:5:
Serializer.h:11:36: error: ‘Storage::UpdateType’ has not been declared
Serializer.h:12:45: error: ‘Storage::UpdateType’ has not been declared
make: *** [main.o] Error 1

任何人都知道这个错误是什么,因为枚举已经声明了。受影响的代码如下:

serializer.h

#ifndef SERIALIZER_H
#define SERIALIZER_H
#include "Storage.h"
class Storage;
class Serializer{
  public: 
    Serializer();
    void serialize(List&, Storage::UpdateType&, std::string&);
    void deserialize(std::string&, Storage::UpdateType&, List&);
};
#endif

存储.h

#ifndef STORAGE_H
#define STORAGE_H 
#include "List.h"
#include "Interface.h"
#include "Movie.h"
#include "Serializer.h"
class Storage{
  public:
    enum UpdateType {ADD, DELETE, RETRIEVE};
    Storage();
    ~Storage();
    List* list;
    void retrieve(List*);
    void update(UpdateType, List*);
    void handleRequest(string&, string&);
  private:
    //Serializer serial;
};
#endif

您遇到的问题是您的代码被解释如下:

#ifndef STORAGE_H
#define STORAGE_H 
// replacing the include with the Serializer.h file
#include "List.h"
#include "Interface.h"
#include "Movie.h"
// replacing the include with the Storage.h file
#ifndef STORAGE_H // returns true
#endif
class Storage;
class Serializer{
  public: 
    Serializer();
    // here Storage::UpdateType is still unknown to the compiler
    void serialize(List&, Storage::UpdateType&, std::string&);
    void deserialize(std::string&, Storage::UpdateType&, List&);
};
#endif

class Storage{
  public:
    // as it gets declared here
    enum UpdateType {ADD, DELETE, RETRIEVE};
    Storage();
    ~Storage();
    List* list;
    void retrieve(List*);
    void update(UpdateType, List*);
    void handleRequest(string&, string&);
  private:
    //Serializer serial;
};
#endif

最好的解决方案是,恕我直言,是从存储类中提取enum UpdateType,然后在Serialializer中向前声明。甚至在序列化器标头中声明它,因为Storage正在封装Serializer的内容,因此基本上,UpdateType的内容应与Serializer材料相同的封装上下文。

另一个解决方案是@nim建议,包括序列化器中的存储,向前声明序列化器在存储中,并将序列化器包括在main中。但这可能会欺骗您认为设计的方式,扭转了SerializerStorage的封装。

最后,我确实不确定这是否可能以及语法如何,但是如果是,则可以简单地将serialializer中的 enum Storage::UpdateType转发。我想这就是您希望的。