例如,如果我有一个构造 Timecode 对象的类,有时我想通过仅为单个参数 (
frameCount
) 提供一个值来初始化实例,而有时则提供多个参数,例如 frameCount
和frameRate
。
这是我尝试过的:
obj := new timecode(2) ;Default to using 12 frames per second
print(obj) ;prints ---> {"frameCount": 24, "framerate": 12}
obj := new timecode(2, 24) ;Use the provided frame rate
print(obj) ;prints ---> {"frameCount": 48, "framerate": 24}
class timecode
{
__New(frames)
{
this.frameCount := frames * 12
this.framerate := 12
}
__New(frames, framerate)
{
this.frameCount := frames * framerate
this.framerate := framerate
}
}
但上面只是抛出一个错误:
==> Duplicate declaration.
Specifically: __New
AutoHotkey closed for the following exit code: 2
我知道 V1 已经像拉丁语一样死了,V2 类现在好多了,但在 V2 的库移植赶上之前,我将使用 V1。
任何帮助将不胜感激!
据我所知,没有直接的方法来创建具有构造函数重载的类。一种可能有效的间接方法如下:
; Define a struct to hold the properties of your "class"
MyClass := {}
; Define a function to act as the constructor
MyClass_New(name := "", age := 0) {
; Initialize a new instance of the class
local obj := {}
; Set the properties based on the arguments passed to the constructor
obj.name := name
obj.age := age
; Return the instance
return obj
}
; Usage:
obj1 := MyClass_New("John", 30)
obj2 := MyClass_New("Jane")