2015-05-24 118 views
1

所以我有類使用超類的構造函數?

(defclass foo() 
    ((a :initarg :a :accessor a) 
    (b :initarg :b :accessor b))) 

(defclass bar (foo) 
    ((c :initarg :c))) 

和構造函數

(defun make-foo (a b) 
    (make-instance 'foo :a a :b b)) 

有沒有一種簡單的方法來定義一個函數,它在現有的FOO併產生BAR與額外的插槽C定義?即而不必列出所有插槽例如:

(defun make-bar-from-foo (existing-foo c) 
    (make-instance 'bar :a (a existing-foo) :b (b existing-foo) :c c)) 
+5

沒有什麼內置。你確定你不想只用'CHANGE-CLASS'將existing-foo改成'bar'嗎? – Barmar

+0

@Barmar哦,不知道'CHANGE-CLASS',謝謝! – wrongusername

+1

CLOS本身沒有構造函數。如果你想要的是一個新的'bar'對象,'change-class'可能不是你想要的,因爲它實際上改變了對象。 – Vatine

回答

0

這可能是一個選項:

(defclass foo() 
    ((a :initarg :a :accessor a) 
    (b :initarg :b :accessor b) 
    (initargs :accessor initargs))) ;Remember the initargs here. 

(defclass bar (foo) 
    ((c :initarg :c :accessor c))) 

(defmethod initialize-instance :after ((foo foo) &rest initargs) 
    (setf (initargs foo) initargs)) 

(defun make-bar-from-foo (foo c) 
    (apply #'make-instance 'bar :c c (initargs foo))) ;And use them here.