【429】关于ADT的访问权限
在看老师代码的时候,发现ADT中的 struct 有时候写到了 adt.c 里面,有时候写到了 adt.h 里面,其实有些困惑,经过仔细研究,发现写在 adt.h 中的 struct 可以在 test.c 中直接使用,而在 adt.c 中的 struct 只有 adt.c 可以使用,因此需要在 adt.h 中定义相应的指针才可以使用。
总结:
- struct 写在 adt.h 中,都可以调用
- struct 写在 adt.c 中,只要 adt.c 可以调用
☀☀☀<< 举例 >>☀☀☀
adt.c 中建立 struct,在 adt.h 建立 指针,但是在 test.c 中无法访问
adt.h
1 2 3 4 5 6 7 8 9 10 | #include <stdio.h> #include <stdlib.h> typedef float Weight; typedef int Vertex; typedef struct edge *Edge; void showEdge(Edge); Edge newEdge(Vertex, Vertex, Weight); |
adt.c
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | #include <stdio.h> #include <stdlib.h> #include "adt.h" struct edge { Vertex v; Vertex w; Weight x; }; Edge newEdge(Vertex v, Vertex w, Weight x) { // create an edge from v to w Edge e = malloc ( sizeof ( struct edge)); e->v = v; e->w = w; e->x = x; return e; } void showEdge(Edge e) { // print an edge and its weight printf ( "%d-%d: %.2f" , e->v, e->w, e->x); return ; } |
test.c
1 2 3 4 5 6 7 8 9 10 | #include "adt.h" int main() { Edge e = newEdge(2, 3, 4); showEdge(e); //printf("\n%d, %d, %0.2f\n", e->v, e->w, e->x); return 0; } |
output:
1 | 2-3: 4.00 |
☀☀☀<< 举例 >>☀☀☀
adt.h 中建立 struct,adt.c 和 test.c 都可以调用,但是相对于安全性较弱
adt.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #include <stdio.h> #include <stdlib.h> typedef float Weight; typedef int Vertex; typedef struct { Vertex v; Vertex w; Weight x; } Edge; void showEdge(Edge); Edge newEdge(Vertex, Vertex, Weight); |
adt.c
1 2 3 4 5 6 7 8 9 10 11 12 13 | #include <stdio.h> #include <stdlib.h> #include "adt.h" Edge newEdge(Vertex v, Vertex w, Weight x) { // create an edge from v to w Edge e = {v, w, x}; return e; } void showEdge(Edge e) { // print an edge and its weight printf ( "%d-%d: %.2f" , e.v, e.w, e.x); return ; } |
test.c
1 2 3 4 5 6 7 8 9 10 | #include "adt.h" int main() { Edge e = newEdge(2, 3, 4); showEdge(e); printf ( "\n%d, %d, %0.2f\n" , e.v, e.w, e.x); return 0; } |
output:
1 2 | 2-3: 4.00 2, 3, 4.00 |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)