Type(临时)
- 来源: https://www.freebasic.net/wiki/wikka.php?wakka=KeyPgTypeTemp
- 最后更新: 2024-12-14
创建用户自定义类型的临时副本
语法
result = Type( initializers, ... )
or
result = Type<typename>( initializers, ... )参数
initializers
类型的初始值(或只是前几个字段的初始值)
typename
Type 或 Union 的名称
返回值
类型的临时副本。
说明
用于创建临时类型。如果没有显式给出 typename,它将尽可能从其用途中推断。临时副本的用法包括将其赋给变量、将其作为参数传递给过程,或从过程中将其作为值返回。
对于没有自有或继承构造函数的类型(也不包括直接或间接派生自 Object 的任何类型),如果所有类型数据字段(包括继承的字段)仅是数值基元类型且没有任何默认初始化器,则允许使用临时类型语法。
如果同时该类型没有析构函数,编译器将直接赋值而不是使用临时副本。
如果该类型有构造函数,且有参数与提供的 initializers 匹配的构造函数,则在创建临时副本时将调用该构造函数;如果该类型有析构函数,则在使用后立即调用析构函数。但当存在匹配的构造函数时,临时类型表达式可以简单地替换为 typename( initializers, ... )。
如果存在至少一个构造函数,但没有与 initializers 匹配的构造函数,则显然不允许使用临时类型语法。
它不仅可以创建用户自定义类型的临时副本,还可以创建预定义数据类型(如可变长度字符串或任何数值数据类型,即所有标准数据类型,不包括固定长度字符串)的临时副本。
它也可以用作比 With 更简短的快捷方式(见下文),如果你要更改所有数据字段(或只是前 n 个字段)。
临时对象在语句执行结束时(定义它的地方)被销毁,但其相应分配的内存不会被释放,并保持可用(未使用)状态,直到离开语句所在的作用域。
在特殊情况下,当在 With 表达式中使用临时类型时,临时类型的销毁推迟到 With 作用域结束。
注意:在过程定义级别使用的 Static 限定符不适用于临时类型。
示例
start GeSHi
Type Example
As Integer field1
As Integer field2
End Type
Dim myexample As Example
'' Filling the type by setting each field
myexample.field1 = 1
myexample.field2 = 2
'' Filling the type by setting each field using WITH
With myexample
.field1 = 1
.field2 = 2
End With
'' Fill the variable's fields with a temporary type
myexample = Type( 1, 2 )end GeSHi
start GeSHi
'' Passing a user-defined types to a procedure using a temporary type
'' where the type can be inferred.
Type S
As Single x, y
End Type
Sub test ( v As S )
Print "S", v.x, v.y
End Sub
test( Type( 1, 2 ) )end GeSHi
start GeSHi
'' Passing a user-defined type to a procedure using temporary types
'' where the type is ambiguous and the name of the type must be specified.
Type S
As Single x, y
End Type
Type T
As Integer x, y
End Type
Union U
As Integer x, y
End Union
'' Overloaded procedure test()
Sub test Overload ( v As S )
Print "S", v.x, v.y
End Sub
Sub test ( v As T )
Print "T", v.x, v.y
End Sub
Sub test ( v As U )
Print "U", v.x, v.y
End Sub
'' Won't work: ambiguous
'' test( type( 1, 2 ) )
'' Specify name of type instead
test( type<S>( 1, 2 ) )
test( type<T>( 1, 2 ) )
test( type<U>( 1 ) )end GeSHi
与 QB 的区别
- FreeBASIC 新增
另请参阅
Type...End TypeType (Alias)
返回 目录