【发布时间】:2018-01-21 13:51:25
【问题描述】:
我对对象(类实例)的行为有疑问。
代码示例:
(defclass game-cards ()
((card-symbol :initarg :card-symbol :accessor card-symbol)
(colour :initarg :colour :accessor colour)))
(defvar *king-hearts* (make-instance 'game-cards
:card-symbol 'King
:colour 'hearts))
(defvar *ace-spades* (make-instance 'game-cards
:card-symbol 'Ace
:colour 'spades))
(defclass game-states ()
((my-cards :initarg :my-cards :accessor my-cards)
(other-cards :initarg :other-cards :accessor other-cards)))
(defparameter *state-1*
(make-instance 'game-states
:my-cards '(*king-hearts* *ace-spades*)
:other-cards ()))
(defmethod play-game ((state game-states))
(some-job (first (my-cards state))))
(defmethod some-job ((card game-cards))
(colour card))
当 some-job 与参数列表中的游戏卡对象一起使用时,它会像我预期的那样工作。
CL-USER> (some-job *king-hearts*)
HEARTS
CL-USER>
这也有效:
CL-USER> (first (my-cards *state-1*))
*KING-HEARTS*
CL-USER>
当我尝试这个时:
(some-job (first (my-cards *state-1*)))
我收到以下错误消息:
There is no applicable method for the generic function
#<STANDARD-GENERIC-FUNCTION COMMON-LISP-USER::SOME-JOB (1)>
when called with arguments
(*KING-HEARTS*).
[Condition of type SIMPLE-ERROR]
当我将 some-job 定义为函数时:
(defun some-job-1 (card)
(colour card))
同样的行为发生。
现在的错误信息是:
There is no applicable method for the generic function
#<STANDARD-GENERIC-FUNCTION COMMON-LISP-USER::COLOUR (1)>
when called with arguments
(*KING-HEARTS*).
[Condition of type SIMPLE-ERROR]
现在*king-hearts* 似乎没有通过某些工作和颜色区分为游戏卡的实例。
是什么原因?为你的答案加油。
【问题讨论】:
-
您不是在传递一个对象,而是在传递一个符号(即变量本身)。您的问题可以简化为
(some-job '*king-hearts*)。 -
试试
:my-cards (list *king-hearts* *ace-spades*)。 -
@melpomene:避免这种情况的正确方法是什么?
-
@melpomene:好的,谢谢你。
标签: common-lisp