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
    
  • 相关阅读:
    jdbc详解(三)
    超文本传输协议-HTTP/1.1
    前人栽树,后人擦屁股
    JAVA 读取计算机中相关信息
    POJ 1836-Alignment(DP/LIS变形)
    【Android】自己定义控件实现可滑动的开关(switch)
    加深理解UIView,UIResponder,UIController
    Fuel4d 2.3 公布
    Android中使用IntentService运行后台任务
    POJ2762 Going from u to v or from v to u? 强连通+缩点
  • 原文地址:https://www.cnblogs.com/alex-bn-lee/p/11295181.html
Copyright © 2011-2022 走看看