Skip to content

CONST(成员)


指定成员过程为只读。

语法

vb
Type typename

Declare Const Sub|Function|Property|Operator ...

End Type

[Const] Sub|Function|... typename ...

...

End Sub|Function|...

说明

指定方法不改变被调用对象。隐藏的 This 参数将被视为只读。该声明可以理解为"调用常量方法承诺不修改对象",如果成员过程试图修改任何数据字段或调用非常量成员过程,编译器将报错。

只读(Const)声明是一种类型安全措施,可以理解为"承诺不修改"。编译器使用常量声明来检查对变量和参数的操作,若其数据可能改变则在编译时生成错误。使用 Const 限定符没有运行时开销,因为所有检查都在编译时进行。

构造函数和析构函数不能是 Const(无意义)。

成员过程不能同时是 ConstStatic,因为静态成员过程没有隐藏的 This 参数。

对于声明中含有 Const 的方法,也可以在对应的方法体上指定 Const,以提高代码可读性。

示例

start GeSHi

vb
'' Const Member Procedures

Type foo
  x As Integer
  c As Const Integer = 0
  Declare Const Sub Inspect1()
  Declare Const Sub Inspect2()
  Declare Sub Mutate1()
  Declare Sub Mutate2()
End Type

''
Sub foo.Mutate1()
  '' we can change non-const data fields
  x = 1

  '' but we still can't change const data
  '' fields, they are promised not to change
  '' c = 1 '' Compile error

End Sub

''
Sub foo.Mutate2()
  '' we can call const members
  Inspect1()

  '' and non-const members
  Mutate1()

End Sub

''
Sub foo.Inspect1()
  '' can use data members
  Dim y As Integer
  y = c + x

  '' but not change them because Inspect1()
  '' is const and promises not to change foo
  '' x = 10 '' Compile error

End Sub

''
Sub foo.Inspect2()
  '' we can call const members
  Inspect1()

  '' but not non-const members
  '' Mutate1() '' Compile error

End Sub

end GeSHi

与 QB 的差异

  • FreeBASIC 新增特性

另请参阅

  • Const
  • Const(限定符)
  • Dim
  • Type

返回 目录

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