当前位置:编程学习 > Delphi >>

delphi与变长参数——开放数组(1)

 

 与C/C++不同,Delphi中是通过可变类型(TVarRec)的开放数组来指定变长参数的。其实这里已经不能称“变长参数”了,因为实际上只传递了一个参数,只是该参数是由多个基础类型数据构成的一个开发数组。Delphi使用开放数组来容纳不定数目的参数,使用可变类型(TVarRec)表示各种类型数据,因此二者的结合可以达到C/C++中变长参数的功能。

       TVarRec是一个记录类型,该记录的VType字段标志记录值的类型,如整数、布尔、字符、实数、字符串、指针、类、类引用、接口、变体等。【注1】

 

 

//这是定义在System 单元关于数据类型的一个结构: 

TVarRec = record 

  case Byte of 

    vtInteger:    (VInteger: Integer; VType: Byte); 

    vtBoolean:    (VBoolean: Boolean); 

    vtChar:       (VChar: Char); 

    vtExtended:   (VExtended: PExtended); 

    vtString:     (VString: PShortString); 

    vtPointer:    (VPointer: Pointer); 

    vtPChar:      (VPChar: PChar); 

    vtObject:     (VObject: TObject); 

    vtClass:      (VClass: TClass); 

    vtWideChar:   (VWideChar: WideChar); 

    vtPWideChar:  (VPWideChar: PWideChar); 

    vtAnsiString: (VAnsiString: Pointer); 

    vtCurrency:   (VCurrency: PCurrency); 

    vtVariant:    (VVariant: PVariant); 

    vtInterface:  (VInterface: Pointer); 

    vtWideString: (VWideString: Pointer); 

    vtInt64:      (VInt64: PInt64); 

end; 

 

       那么开放数组又是什么?关于开放数组,官方文档给出的解释是:

(1)Object Pascal has an “open array” construct that permits an array of unspecified size to be passed to a function.

面向对象Pascal有一个开放数组的概念允许向一个方法传递未指定大小的数组。

(2)an Object Pascal function that has an open array parameter can be called by explicitly passing both the pointer to the first element of an array and the value of the last index (number of array elements, minus one).

一个面向对象的含有开放数组参数的Pascal函数能通过传递数组的第一个元素的地址和最后一个元素的索引(即数组大小减1)来调用。

 

 

 

//官方例子 

//Object Pascal声明 

function  Mean(Data:  array of  Double): Extended; 

//Pascal调用 

Result := Mean([3.1, 4.4, 5.6]); 

 

//官方例子 

//C++声明 

Extended  __fastcall  Mean( const double  * Data,  const int  Data_Size); 

//C++调用 

double  d[] = { 3.1, 4.4, 5.6 } ;  

return  Mean(d, 2) ;  

       看了官方文档还是一头雾水,根本就没解释什么是开放数组。好像开放数组与动态数组是一样的嘛!在Delphi中,数组类型有静态数组(array[0..1024] of integer)、动态数组(array of integer)两类。关于动态数组,官方文档给出的解释是:

(3)Dynamic arrays do not have a fixed size or length. Instead, memory for a dynamic array is reallocated when you assign a value to the array or pass it to the SetLength procedure.

动态数组没有固定大小或长度。你可以通过给动态数组赋值或使用SetLength方法给动态数组重新分配内存。

 

 

 

//定义动态数组变量 

var MyFlexibleArray: array of Real; 

//分配内存 

SetLength(MyFlexibleArray, 20);   

 

   动态数组

补充:软件开发 , Delphi ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,