初始化作为另一个 ISO C++成员的结构

Initializing a struct which is a member of another ISO C++

本文关键字:成员 结构 C++ ISO 另一个 初始化      更新时间:2023-10-16

我有两个结构:

    struct port
{
    bool isOutput;
    bool isConnected;
    int connwires;
};
struct node
{
    port p;
    vector<Wire*> w;
};

我有:

    node *nodes;

在我的课堂上。问题是如何初始化由以下人员创建的所有n个节点结构的端口成员(p):

    nodes= new node[n];

类构造函数中的语句。

(我像这样定义端口结构:

    struct port
{
    bool isOutput=0;
    bool isConnected=0;
    int connwires=0;
};

但它在"ISO C++"中无效。

谢谢。

您需要

提供一个默认构造函数,以便port自动初始化其成员

struct port
{
    port() :
        isOutput(false),
        isConnected(false),
        connwires(0)
    { }
    bool isOutput;
    bool isConnected;
    int connwires;
};
请注意,您的

最后一个代码是有效的,并且自 C++11 以来执行了您的预期。