自指结构
Self referential Structure
本文关键字:结构 更新时间:2023-10-16
我正在为自引用结构编写 2 个代码:
第一:
struct node
{
int a;
struct node *link;
};
int main()
{
struct node n;
n.a = 5;
cout<< n.a << "t" ;
cout << n.link ;
return 0;
}
输出 : ̀ 5 0x40185b'
第二:
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;
}
仅当n.link
指向有效的node
对象时,*(n.link)
才有效。并且cout << *(n.link);
只有在您声明node
的operator<<
时才有效(cout << n.link;
有效,因为它输出地址,而不是值)。
例如,这会更好:
#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;
}
它输出5 -> 6 -> NULL
相关文章:
- 如何循环打印顶点结构
- 通过方法访问结构
- 使用不带参数的函数访问结构元素
- 预处理器:插入结构名称中的前一个行号
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 孤立代码块在结构中引发异常
- 有什么方法可以遍历结构吗
- 如何在 C# 中映射双 C 结构指针?
- 如何在C++中使用结构生成映射
- 无法将结构注册为增强几何体3D点
- 多成员Constexpr结构初始化
- C++将文本文件中的数据读取到结构数组中
- 如何重构类层次结构以避免菱形问题
- 如何在C++中序列化结构数据
- std::vector的包装器,使数组的结构看起来像结构的数组
- 没有为自己的结构调用列表推回方法
- 奇怪的结构&GCC&clang(void*返回类型)
- 在 c++ 中拥有一组结构的正确方法是什么?
- vscode g++链路故障:体系结构x86_64的未定义符号
- C++概念:如何使用'concept'检查模板化结构的属性?