Skip to content

CAST


将表达式转换为指定的数据类型

语法

Cast( datatype, expression )

参数

datatype

内置数据类型(标准类型)

expression

另一种内置数据类型的变量

说明

expression 转换为不同的 datatype。在宏中 datatype 未知时以及转换为类型别名时非常有用。

这是 CintCdbl 等转换运算符的通用形式。

Cast 更加灵活,因为它可以用于具有内置 Cast 运算符 但没有内置关键字的内置类型:例如 Cast( Byte, boolean )

它还适用于代码中变量类型不固定的情况——例如,它可能是之前 Define 的,或者可能是不同变量或表达式的 Type of

注意:如果你想使用专门用于转换到不同类型 Pointer 的运算符,请考虑使用 Cptr

向上转型:在继承结构中,向上转型是将派生类型引用或指针转换为基类类型。

在这种特殊用法中,对派生类型实例(expression)应用 Cast 可用于返回基类类型(datatype)引用。

通过使用成员 Operator Cast,可以为用户自定义类型表达式重载 Cast

示例

start GeSHi

vb
'' will print -128 because the integer literal will be converted to a signed Byte
'' (this Casting operation is equivalent to using CByte)
Print Cast( Byte, &h0080 )

'' will print 3 because the floating-point value will be converted to an Integer
'' (this Casting operator is equivalent to using CInt)
Print Cast( Integer, 3.1 )

Sleep

end GeSHi

start GeSHi

vb
'' macro sizeofDerefPtr(): returns the size of the dereferenced pointer
#define sizeofDerefPtr(ptrToDeref) SizeOf(*Cast(TypeOf(ptrToDeref), 0))

'' macro typeofDerefPtr(): returns the type of the dereferenced pointer
#define typeofDerefPtr(ptrToDeref) TypeOf(*Cast(TypeOf(ptrToDeref), 0))

' Allocate dynamically memory for a Double by New
Dim As Double Ptr pd
pd = New typeofDerefPtr(pd)
*pd = 3.14159
Print *pd

' Allocate dynamically memory for a Zstring*10 by Callocate
Dim As ZString Ptr pz
pz = CAllocate(10, sizeofDerefPtr(pz))
*pz = "FreeBASIC"
Print *pz

Sleep
Delete pd
Deallocate(pz)

end GeSHi

方言差异

  • -lang qb 方言中不可用,除非使用别名 __Cast 引用。

与 QB 的差异

  • FreeBASIC 新增特性

另请参阅

返回 目录

基于 FreeBASIC 官方文档翻译 如有侵权请联系我们删除
FreeBASIC 是开源项目,与微软公司无隶属关系