我找不到在 Racket 中定义静态字段的方法。通过静态,我的意思是属于整个类而不是实例的字段。
(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)
最佳答案
这个解决方案怎么样?
#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)
关于oop - 我可以在 Racket 类中定义静态字段吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52483487/