【问题标题】:Struct to hold the data of the same struct typestruct 保存相同结构类型的数据
【发布时间】:2019-08-28 10:44:03
【问题描述】:

我正在尝试创建一个必须保存相同结构类型的数据的结构。这可能吗?

我可以定义指向同类型对象的指针,但不能定义结构本身。

struct Node
{
    vector<string> state;
    struct Node *prev;
    int id;
    Node()
    {
    }

    ~Node()
    {
    }
};

这是可能的。但我不能像下面这样定义。执行时出现“不允许不完整类型”的错误。

struct Node
{
    vector<string> state;
    struct Node prev;
    int id;
    Node()
    {
    }

    ~Node()
    {
    }
};

这可能吗?如果是,我应该怎么做才能摆脱错误?

我已经看到这在 Java 中使用类是可能的,

public class Vertex implements Comparable{

    public Pallet[] bins;
    public int cost;
    public Vertex parent;
}

谢谢

【问题讨论】:

标签: c++11 struct


【解决方案1】:

没有。

struct Node
{
    vector<string> state;
    struct Node prev;
    int id;
    Node()
    {
    }

    ~Node()
    {
    }
};

此代码不起作用,因为 Node 类型不知道为 Node 类型的对象分配多少空间。该类型仍在定义过程中。因此,它还不知道。

但是,我可以用指针做到这一点!?

是的。指针保存的不是对象,而是对象的内存位置。编译器知道 Node 是一种数据类型,但它不需要知道要分配多少,因为分配将在以后手动完成。

但是,我可以用 Java 做到这一点!?

Java 中的引用不同于 C++ 指针 (What is the difference between a pointer and a reference variable in Java? )。但是,出于许多目的,您可以将它们视为相同的。请记住,当您在 Java 类中创建成员时,您就是在创建引用。 (How can a class have a member of its own type, isn't this infinite recursion?)。 Java 引用将引用(指向)实际对象。 Java 类中的成员“父级”不是对象本身,而是对对象的引用。与 C++ 类中的“*prev”相同的方式不是对象,而是指向对象的位置。

【讨论】:

    猜你喜欢
    • 2012-01-07
    • 2020-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-29
    • 1970-01-01
    相关资源
    最近更新 更多