初始化

出自維基百科,自由嘅百科全書
Jump to navigation Jump to search

初始化粵拼co1 ci2 faa3美式英文initialization英式英文initialisation)係電腦編程上嘅一個程序,指為啲變數設定初始嘅數值,而喺物件導向程式編寫當中,初始碼包括咗將個程式要用嘅物件定義同埋建構出個體物件[1]。初始化嘅過程可以喺個程式做編譯嗰陣做,又可以喺執行期(run time)嗰時做。一段碼當中負責做初始化嗰橛仔就係所謂嘅初始化碼(initialization code)[1]。初始化嘅相對係最終化(finalization)。

喺實際程式編寫上,好多程式語言都會有特定嘅建構用嚟做初始化,而呢啲建構就係所謂嘅初始化器(initializer)或者初始化列表(initializer list),但詳細嘅初始化程序可能依程式語言或者初始化緊嘅物件種類而有所不同[2]

例子碼[編輯]

喺多數嘅高階程式語言當中,個程式頭嗰若干行多數都係用嚟做初始化嘅;初始化通常涉及若干行嘅碼,每行都用「=」嚟將柞變數同物件設起初始嘅數值(喺多數高階程式語言裏面,「x = y」表達嘅係「將 x 呢個變數設做 y 呢個數值」)。以下係多種常用程式語言裏面做嘅初始化,定義一啲(個程式跟住落嚟會用嘅)變數、排列、同物件等[3]

C
   /* variables */
   int a = 2;
   int b;
   b = 20;
   char string1 = 'a';
   char string2 = 'f';

   /* arrays and matrices */
   float mark[5] = {19, 10, 8, 17, 9};
   int markagain[3][4] = {  
      {0, 1, 2, 3} ,   /*  initializers for row indexed by 0 */
      {4, 5, 6, 7} ,   /*  initializers for row indexed by 1 */
      {8, 9, 10, 11}   /*  initializers for row indexed by 2 */
   };

   /* structs */
   struct point {int x; int y;};
   struct point p = {1, 3};
C++
  // variables
  int a, b;
  int result = 10;
  a = 5;
  b = 2;

  // arrays and matrices
  int i[] = { 10, 20, 30 };
  int j [3][4] = {  
      {0, 1, 2, 3} ,   //  initializers for row indexed by 0
      {4, 5, 6, 7} ,   //  initializers for row indexed by 1 
      {8, 9, 10, 11}   //  initializers for row indexed by 2
   };

  // structs
  struct point {int x; int y;};
  struct point p = {1, 3};
Python
  # variables
  result = 10
  a = 5
  b = 2

  # arrays and matrices
  i = [1, 2, 3]
  j = [[0 for x in range(5)] for y in range(5)] # a 5 x 5 matrix, all elements being 0.

  # structs
  class stru:
      def __init__(self):
          self.x = 0
          self.y = 0
  s = stru()
  s.x = 10
MATLAB
  % variables
  result = 10;
  a = 5;
  b = 2;

  % arrays and matrices
  i = zeros(5,1); # a 5-item array, all elements being 0.
  j = zeros(5,5); # a 5 x 5 matrix, all elements being 0.

  % structs
  s.x = 1;
  s.y = {'A','B','C'};
Processing
  // variables
  int a = 100;
  int b = 100;

  // arrays and matrices
  int[] i = new int[3];
  int[][] j = {  {0, 1, 2, 3},
                     {3, 2, 1, 0},
                     {3, 5, 6, 1},
                     {3, 8, 3, 4}  };

睇埋[編輯]

參考書[編輯]

  • A.K. Hartmann, Practical Guide to Computer Simulations, Singapore: World Scientific (2009).

[編輯]

  1. 1.0 1.1 Boehm, Hans-J. (2002). Destructors, Finalizers, and Synchronization. POPL.
  2. Variable Initialization in C programming language.
  3. C++ FAQs, by Cline, Lomow, and Girou, Addison-Wesley, 1999.