SOGO論壇
  登入   註冊   找回密碼
查看: 555|回覆: 0
列印 上一主題 下一主題

[技術文章] 物件的區域性與全域性 [複製連結]

Rank: 11Rank: 11Rank: 11Rank: 11

熱心參予論壇活動及用心回覆主題勳章 數位硬體勳章

狀態︰ 離線
跳轉到指定樓層
1
發表於 2012-7-21 10:19:55 |只看該作者 |倒序瀏覽
不僅變數的 宣告或定義 具有 區域性與全域性, 事實上任意一 辨識體(物件) 如 struct、 typedef、 enum、 巨集的宣告、 函數的定義等,其 使用範圍的規則 也相同。

C 程式 函數的定義不像 Pascal,函數 不能 定義在 另一個函數之內。因此,函數都具有 全域性。 一般而言, 我們會宣告一個函數 在 檔頭或 在一個 block 的開頭,如:

例 4.

int square(int i);  或  main()
main()                  { int square(int i);
{ int i=10,j=2;           int i=10,j=2;
  j=square(i);            j=square(i);
}                       }
int square()            int square(int i)
{return i*i;}           {return i+i;}

通常 一個程式的設計,可 能會因性質的不同 而 將 程式碼 分散於 不同的檔案,對於一些常數的定義, 全域變數的宣告, 函數的宣告, 資料型態的設定 都放在 檔頭檔,以 #include 的方式 來達到 宣告的一致性。我們將於第 10 章 來 介紹 程式設計的一些技巧。

例 5. 設檔案 file.txt 含下列內容:


#include< stdio.h >
struct point {int x,y;};
struct rect {point topLeft, bottomRight};
int pointInRect(struct point, stuct rect);
extern point currentLoc;

設檔案 file.c 含下列內容:

#include "file.txt"
point currentLoc;

int pointInRect(struct point p, stuct rect r)
{  int x1,x2,y1,y2;
   if(r.topLeft.x < r.bottomRight.x)
   { x1=r.topLeft.x; x2=r.bottomRight.x;}
   else
   { x2=r.topLeft.x; x1=r.bottomRight.x;}

   if(r.topLeft.y < r.bottomRight.y)
   { y1=r.topLeft.y; y2=r.bottomRight.y;}
   else
   { y2=r.topLeft.y; y1=r.bottomRight.y;}

   if(x1 <= p.x && p.x <= x2 && y1 <=p.y && p.y <= y2)
        return 1;
   else return 0;
}

設檔案 main.c 含下列內容


#include "file.txt"
main()
{ struct rect r;

  r.topLeft.x=10; r.topLeft.y=10;
  r.bottomRight.x=20; r.bottomRight.y=20;

  scanf("%d %d", &currentLoc.x, &currentLoc.y);

  if(pointInRect(currentLoc,r))
     printf("in the rectangle\n");
  else
     printf("not in the rectangle\n");
}

說明:

檔案 file.c 含 全域變數 currentLoc 的定義。
檔案 file.txt 含全域變數 currentLoc 的宣告,即 extern point currentLoc,其中 extern 表示 全域變數定義 於它處。
檔案 file.txt 含函數 pointInRect 的宣告,即 int pointInRect(struct point,struct rect);。
資料型態 struct point 及 struct rect 都宣告於檔案 file.txt 中, file.c 與 main.c 皆有 #include 指令 "file.txt",因此可直接使用 struct point 及 struct rect。
喜歡嗎?分享這篇文章給親朋好友︰
               感謝作者     

請注意︰利用多帳號發表自問自答的業配文置入性行銷廣告者,將直接禁訪或刪除帳號及全部文章!
您需要登錄後才可以回覆 登入 | 註冊


本論壇為非營利自由討論平台,所有個人言論不代表本站立場。文章內容如有涉及侵權,請通知管理人員,將立即刪除相關文章資料。侵權申訴或移除要求:abuse@oursogo.com

GMT+8, 2024-4-28 17:58

© 2004-2024 SOGO論壇 OURSOGO.COM
回頂部