C++编译错误C2146和C4430



编译器显示了两个错误:C2146-语法错误:缺少";"在标识符"begin"之前C4430-缺少类型说明符-假定为int。注意:C++不支持默认的int错误出现在我的"Globals.h"文件的第5行。就在这里:

#pragma once
#include "Load.h"
#include "SortStream.h"
extern Load begin;
extern int sort_by;
extern int sort_type;
extern vector<Flight> all_flights;
extern SortStream sort_stream;

我的"Globals.cpp"文件看起来像:

#include "Globals.h"
Load Begin;
int sort_by;
int sort_type;
vector<Flight> all_flights;
SortStream sort_stream;

而ofc,这里是"Load.h"文件:

#pragma once
#include <vector>
#include "Flight.h"
#include "Globals.h"
using namespace std;
class Load {
    std::string path;
    vector<Flight> allFlights;
public:
    Load();
   std::string get_path();
   vector<Flight> get_allFlights();
   void set_path(std::string p);
   void set_allFlights(vector<Flight> v);
   void load_flights();
};

"SortStream.h"文件:

#pragma once
#include <vector>
#include "Flight.h"
using namespace std;
class SortStream {
    vector< vector < Flight > > layout;
    int switchNum;
    int iterationNum;
    int compareNum;
public:
    SortStream();
    vector< vector < Flight > > get_layout();
    int get_switchNum();
    int get_iterationNum();
    int get_compareNum();
    void set_layout(vector< vector < Flight > > v);
    void set_switchNum(int n);
    void set_iterationNum(int n);
    void set_compareNum(int n);
};

有人知道原因吗?Tnx提前

要看到失败,您必须了解#includes是如何工作的。每个#include都被包含文件的副本所替换。

查看Load.h

#pragma once
#include <vector> <-- paste vector in here
#include "Flight.h" <-- paste Flight.h in here
#include "Globals.h" <-- paste Globals.h in here
using namespace std;
class Load {
    std::string path;
    vector<Flight> allFlights;
public:
    Load();
   std::string get_path();
   vector<Flight> get_allFlights();
   void set_path(std::string p);
   void set_allFlights(vector<Flight> v);
   void load_flights();
};

让我们粘贴到Globals.h中,看看会发生什么:

#pragma once
#include <vector> <-- paste vector in here
#include "Flight.h" <-- paste Flight.h in here
//Globals.h begins here
#pragma once
#include "Load.h" <-- would paste Load.h in here, but it's protected by #pragma once 
                      and will not be pasted in again
#include "SortStream.h" <-- paste SortStream.h in here
extern Load begin;
extern int sort_by;
extern int sort_type;
extern vector<Flight> all_flights;
extern SortStream sort_stream;
// end of Globals.h
using namespace std; <-- off topic: Very dangerous thing to do in a header
class Load {
    std::string path;
    vector<Flight> allFlights;
public:
    Load();
   std::string get_path();
   vector<Flight> get_allFlights();
   void set_path(std::string p);
   void set_allFlights(vector<Flight> v);
   void load_flights();
};

在这种情况下,我们可以看到在定义Load之前引用了Load begin;。繁荣

循环引用几乎总是不好的,在这种情况下,它是致命的。换句话说,塔里克·尼杰赢得了胜利。

Load.h不需要在Globals.h中定义任何内容,因此删除include以打破循环。

相关内容

  • 没有找到相关文章

最新更新