1. 程式人生 > 其它 >Delphi Records與classes幾點不同

Delphi Records與classes幾點不同

Though records can now share much of the functionality of classes, there are some important differences between classes and records. 
Records do not support inheritance.
Records can contain variant parts; classes cannot.
Records are value types, so they are copied on assignment, passed by value, and allocated on the stack unless they are declared globally or explicitly allocated using the New and Dispose function. Classes are reference types, so they are not copied on assignment, they are passed by reference, and they are allocated on the heap.
Records allow operator overloading on the Win32 platform; classes, however, do not allow operator overloading.
Records are constructed automatically, using a default no-argument constructor, but classes must be explicitly constructed. Because records have a default no-argument constructor, any user-defined record constructor must have one or more parameters.
Record types cannot have destructors.
Virtual methods (those specified with the virtual, dynamic, and message keywords) cannot be used in record types.
Unlike classes, record types on the Win32 platform cannot implement interfaces.

儘管reords目前可以使用許多classes的特性,但是還是有幾點重要的不同

  1. records不支援繼承
  2. records可以包含variant classes不能
  3. records是值型別,所以在賦值時會直接複製其值。預設在棧stack上分配儲存空間,或者使用new,dispose進行分配。classes是引用型別,其賦值時傳遞是引用。在堆heap上分配
    1. 棧由系統核心管理
    2. 堆程式自動來分配,程式退出時,系統回收。容易造成記憶體洩露
  4. records在win32平臺支援操作符過載
  5. records自動執行一個沒有引數的建構函式進行構建。類需要顯示的執行建構函式。因為record有一個預設無參的建構函式,所以使用者定義的record如果建構函式,其必需有至少一個引數
  6. records不能析構
  7. records中不能使用虛方法
  8. records不能實現介面
酒肉穿腸過 佛祖心中留 世人若學我 如同入魔道