C++ 自指结构

C++ 自指结构,c++,C++,我正在为自指结构编写两个代码: 第一: struct节点 { INTA; 结构节点*链接; }; int main() { 结构节点n; n、 a=5; 我想这就是你想要做的: int main(){ struct node n; n.a = 5; n.link = NULL; // initialize the link cout << n.a << "\t"; cout << n.link; return

我正在为自指结构编写两个代码:

第一:

struct节点
{
INTA;
结构节点*链接;
};
int main()
{
结构节点n;
n、 a=5;

我想这就是你想要做的:

int main(){

    struct node n;
    n.a = 5;
    n.link = NULL; // initialize the link
    cout << n.a << "\t";
    cout << n.link;

    return 0;

}

它输出<代码> 5 > ->空> < /p> <代码>错误:链接在这个范围内没有声明。< /CUT>这是运行时错误吗?看起来不一样。读一本好的C++编程书,然后查看一些;你的问题需要一些,而且是离题的有趣的,我得到完全不同的错误,因为这是C++,你应该使用<代码>节点A1;< /C>不是
struct node a1
。如果在底部写
std::cout
,也可以使用命名空间std
删除
。@MartinBonner:是的,修复了这个问题
struct node{

    int a;
    struct node *link;

};

int main(){

    struct node n;

    n.a = 5;

    cout << n.a << "\t";

    cout << *n.link ;

    return 0;

}
int main(){

    struct node n;
    n.a = 5;
    n.link = NULL; // initialize the link
    cout << n.a << "\t";
    cout << n.link;

    return 0;

}
#include <iostream>

struct node{
    int a;
    node *link; // Note: no need to prefix with struct
};

std::ostream& operator<<( std::ostream& str, const struct node& n )
{   
    str << n.a << "\t -> ";
    if ( n.link )
        str << *n.link;
    else
        str << "NULL";

    return str;
}

int main(){

    node n1; // Note: no need to prefix with struct
    node n2; // Note: no need to prefix with struct

    n1.a = 5;
    n1.link = &n2;

    n2.a = 6;
    n2.link = NULL;

    cout << n1;

    return 0;

}