【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
#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
#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
#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:
2-3: 4.00
☀☀☀<< 举例 >>☀☀☀
adt.h 中建立 struct,adt.c 和 test.c 都可以调用,但是相对于安全性较弱
adt.h
#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
#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
#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:
2-3: 4.00 2, 3, 4.00
浙公网安备 33010602011771号