【问题标题】:How can I tell compiler there is some struct not defined but will?我如何告诉编译器有一些未定义但会定义的结构?
【发布时间】:2021-01-30 14:07:38
【问题描述】:
#include<vector>
struct EDGE {
    VERTEX* from;
    VERTEX* to;
    int weight;
};
struct VERTEX {
    std::vector<EDGE*> edges;
};
struct MAP{
    std::vector<VERTEX> vertex;
    bool directed{ false };
}map;

我想用这些数据上课。 如何使用未定义的类但将被定义?

【问题讨论】:

  • 你能附加更多编写类的代码吗?我不确定undefined class but will be define 是什么意思。在这些结构下面写类不是你的情况吗?
  • 转发声明它就像你声明一个函数一样。 struct VERTEX;,然后是EDGE的定义,以此类推。
  • 这是导致编译器错误的所有代码。我想在 EDGE 中使用 VERTEX*,但尚未定义 VERTEX,因此编译器会生成 error_issue。我使用 MS Visual Studio。
  • 谢谢。我可以告诉它,就像 tell func 一样!谢谢!。@内森·皮尔森
  • @Lorne 是的。我得到了它。谢谢!

标签: c++ class struct compiler-errors


【解决方案1】:

您需要一种称为前向声明的技术。代码如下所示:

#include<vector>

// forward declaration of VERTEX
struct VERTEX; 

struct EDGE {
    VERTEX* from;
    VERTEX* to;
    int weight;
};

// actual definition of VERTEX
struct VERTEX {
    std::vector<EDGE*> edges;
};

struct MAP{
    std::vector<VERTEX> vertex;
    bool directed{ false };
} map;

但这只有在你使用指向前向声明类的指针时才有效。编译器需要知道成员的确切大小。指针的大小总是已知的,它不依赖于它指向的东西。所以它有效。但是这段代码不会编译,因为VERTEXincomplete type,它的大小是未知的:

// forward declaration of VERTEX
struct VERTEX; 

struct EDGE {
    VERTEX from; // the VERTEX is incomplete type here
    VERTEX to;
    int weight;
};

【讨论】:

  • 哦,我明白了。这取决于编译器应该分配多少内存!多谢。我了解它为什么会导致错误以及如何修复有关错误的程序。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-16
  • 1970-01-01
相关资源
最近更新 更多