zoukankan      html  css  js  c++  java
  • 【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("
    %d, %d, %0.2f
    ", 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("
    %d, %d, %0.2f
    ", e.v, e.w, e.x);
    	
    	return 0;
    }
    

    output:

    2-3: 4.00
    2, 3, 4.00
    
  • 相关阅读:
    SQL Server:创建索引视图
    Asp.Net常用函数
    SQL Server联机丛书:删除存储过程
    音乐知识全接触
    深入透析样式表滤镜
    有一天,爸妈会变老
    今天终于买到票啦~~
    今天,回到上海啦~~(附工作生涯回顾)
    十八问:怎么才是喜欢编程
    把旧光驱改CD播放机的方法
  • 原文地址:https://www.cnblogs.com/alex-bn-lee/p/11295181.html
Copyright © 2011-2022 走看看