2015-05-24 119 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.