/****************1.介面
*******************/
用乙個例子說明介面中所使用的一些約定:
#ifndef arith_h
#define arith_h
extern
int arith_max(int x, int y);
extern
int arith_min(int x, int y);
extern
int arith_div(int x, int y);
extern
int arith_mod(int x, int y);
extern
int arith_ceiling(int x, int y);
extern
int arith_floor(int x, int y);
#endif
介面名字以字首的形式出現在介面的每乙個識別符號中,因為在檔案範圍內所有識別符號----變數,函式,型別定義以及列舉常量共享乙個專用的名字空寂,而所有的全域性結構,結構體,共用體以及列舉標籤共享另乙個專用的名字空間,所以為了防止名字衝突,採取這種方法。
對於x和y不同符號時,以上幾種運算可能在不同編譯器下出現不同的結果,所以在實現的時候需要注意。
arith_div是用更精確的數學術語定義的,arith_div(x,y)是不超過實數z的最大整數,其中z.y=x.
而c中的內嵌操作,如-13/5則是向0取整,故-13/5=-2。
/*************2.實現*****************/
#include "arith.h"
#include
int arith_max(int x, int y)
int arith_min(int x, int y)
int arith_div(int x, int y)
int arith_mod(int x, int y)
int arith_floor(int x, int y)
int arith_ceiling(int x, int y)
int main(int argc,char* argv)
乙個介面可能有多個實現,但其定義要符合介面的宣告,然而c語言中並沒有提供某種機制檢查實現的一致性
/***************3.堆疊***************/
我們再來看乙個關於抽象資料型別(adt)的例子:stack
先看介面:
#ifndef stack_included
#define stack_included
#define t stack_t
/*typedef定義了stack_t型別,該型別是乙個指向有相同名字標籤的結構*/
typedef struct t *t;
/*這裡stack_t是乙個隱式的指標型別*/
extern t stack_new (void);
extern
int stack_empty(t stk);
extern
void stack_push (t stk, void *x);
extern
void *stack_pop (t stk);
extern
void stack_free (t *stk);
#undef t
#endif
很簡潔,也無需贅述。再來看看實現
#include
#include "assert.h"//該書作者自己寫的標頭檔案
#include "mem.h" //該書作者自己寫的標頭檔案
#include "stack.h"
#define t stack_t
struct t
*head;
};//勿忘
t stack_new(void)
int stack_empty(t stk)
void stack_push(t stk, void *x)
void *stack_pop(t stk)
void stack_free(t *stk)
free(*stk);
}當乙個抽象資料型別用隱式指標表示時,返回的型別也是乙個指標型別,所以把stack_t定義為乙個指向結構體stack_t的指標,所以以上表示式中,stk可以用用->符號獲取結構體元素
GO 語言程式設計讀書筆記 介面值
從概念上來講,乙個介面型別的值 簡稱介面值 其實有兩個部分 乙個具體型別和該型別的乙個值。二者稱為介面的動態型別和動態值。比如下面宣告乙個介面變數 w 並賦值,那麼 w 介面值可以用如下圖表示 介面的零值 介面的零值就是把它的動態型別和動態值都設為 nil,如下圖所示 var w io.writer...
讀書筆記 設計模式 介面與抽象類
客戶物件 乙個請求其他物件的服務的物件稱為客戶物件。物件a呼叫了物件b的方法,稱a為客戶物件。定義乙個計算員工薪水的介面,由於有不同的員工,若將計算方法都放在員工類的內部,不利於 的維護。public inte ce salarycal public double getsalary public ...
c語言介面與實現
分類 程式設計 2006 04 13 21 57 7392人閱讀收藏 舉報 語言c 資料結構 c lua exception 書中對atom,list,stack,hashtable,set,ring,exception等都作了 相信看過這邊書後,你使用c程式設計的功力會大為提高。也許使用c 的朋友...