1

我正在阅读Sonja Keene的 Common Lisp 中的面向对象编程一书。

在第 7 章中,作者提出:

(class-name class-object)

这将使查询类对象的名称成为可能。

使用 SBCL 和 SLIME 的 REPL,我尝试了:

; SLIME 2.26.1
CL-USER> (defclass stack-overflow () 
           ((slot-1 :initform 1 )
            (slot-2 :initform 2)))
#<STANDARD-CLASS COMMON-LISP-USER::STACK-OVERFLOW>
CL-USER> (make-instance 'stack-overflow)
#<STACK-OVERFLOW {1002D188E3}>
CL-USER> (defvar test-one (make-instance 'stack-overflow))
TEST-ONE
CL-USER> (slot-value test-one 'slot-1)
1
CL-USER> (class-name test-one)
; Evaluation aborted on #<SB-PCL::NO-APPLICABLE-METHOD-ERROR {10032322E3}>.

上面的代码返回下面的错误信息:

There is no applicable method for the generic function
  #<STANDARD-GENERIC-FUNCTION COMMON-LISP:CLASS-NAME (1)>
when called with arguments
  (#<STACK-OVERFLOW {1003037173}>).
   [Condition of type SB-PCL::NO-APPLICABLE-METHOD-ERROR]

如何正确使用class-name

谢谢。

4

2 回答 2

5

to 的参数class-name必须是类对象,而不是类的实例。

用于class-of获取实例的类,然后可以调用class-name

(class-name (class-of test-one))
于 2021-09-30T18:52:44.007 回答
0

在评论中使用@Barmar 的提示,这将是正确的方法class-name

CL-USER> (class-name (defclass stack-overflow () 
                       ((slot-1 :initform 1 )
                        (slot-2 :initform 2))))
STACK-OVERFLOW

class-name接收一个类作为参数。为了使用实例,正确的方法是使用class-of

CL-USER> (class-of 'test-one)
#<BUILT-IN-CLASS COMMON-LISP:SYMBOL>

不过,我不确定为什么class-name会有帮助。

于 2021-09-30T18:52:58.577 回答