我找不到在球拍中定义静态字段的方法。静态是指属于整个类而不是实例的字段。
(define counter% (class object%
(field (current-count 0))
(super-new)
(define/public (get-count)
current-count)
(define/public (next)
(set! current-count (+ current-count 1))
(set! total (+ total 1))
(list current-count total))))
(define c1 (new counter%))
(define c2 (new counter%))
(send c1 next)
(send c1 next)
(send c1 next)
(send c2 next)
因此,本示例中的total
应该是静态字段,输出应该是:
'(1 1)
'(2 2)
'(3 3)
'(1 4)
答案 0 :(得分:2)
该解决方案如何?
#lang racket
(define counter%
(let ([total 0])
(class object%
(field (current-count 0))
(super-new)
(define/public (get-count)
current-count)
(define/public (next)
(set! current-count (+ current-count 1))
(set! total (+ total 1))
(list current-count total)))))
(define c1 (new counter%))
(define c2 (new counter%))
(send c1 next)
(send c1 next)
(send c1 next)
(send c2 next)