首页 > 解决方案 > 是否存在插槽不会被初始化为其 initform 的情况?

问题描述

我正在尝试了解 CLOS,并编写了一个示例类。它有 4 个插槽,命名为 slot1-4。slot2 有一个 initform,但我仍然收到此错误:“插槽 COMMON-LISP-USER::SLOT2 在对象中未绑定”。我看不出这是怎么可能的。我正在使用 SBCL,我的代码如下:

;;;; The following is meant to demonstrate some concepts of object initialisation
(defclass example ()
  ((slot1
    :initarg :slot1-arg
    :initform (error "must supply a slot1"))
   (slot2
    :initform "This is the initform"
    :reader slot2-reader
    :writer (setf slot2-writer))
   (slot3
    :accessor slot3-accessor
    :documentation "The third slot")
   (slot4)))

(defmethod initialize-instance :after ((instance example) &key)
  (setf (slot-value instance 'slot4)
        "this was set in INITIALIZE-INSTANCE"))

(let ((xampl (make-instance 'example
                            :slot1-arg "Must provide this or there will be an error")))
  (setf (slot3-accessor xampl)
        "it is necessary to initialize this slot, as there is not initform or initarg")
  (print (slot3-accessor xampl))
  (setf (slot-value xampl 'slot3) "this also works")
  (print (slot-value xampl 'slot3))
  (print (slot2-reader xampl)))

标签: lispcommon-lispclos

解决方案


推荐阅读