假设你有一个基本包,它可以通过一个类和另一个想要扩展这种能力的包来表示某些东西。
(defpackage :test
(:use :cl)
(:nicknames :test)
(:export a-test-class
method-a
slot-a))
(in-package :test)
(defclass a-test-class ()
((slot-a
:initform 42
:reader slot-a)))
(defmethod method-a ((a-test-class a-test-class))
(setf (slot-value a-test-class 'slot-a) 21)
a-test-class)
(defpackage :exttest
(:use :cl)
(:export extended-a-test-class
method-a))
(in-package :exttest)
(defclass extended-a-test-class (test:a-test-class)
((slot-b
:reader slot-b
:initform nil)))
(defmethod method-a ((a-test-class extended-a-test-class))
(setf (slot-value a-test-class 'slot-a) 23)
a-test-class)
现在我得到了一个函数,它并没有真正做任何事情,而是遍历 and 的实例列表, a-test-class
并且extended-a-test-class
应该调用method-a
所有这些实例,期望它们分别更改为它们的类型。例如(slot-a (method-a a-test-class-instance)) > 21
和(slot-a (method-a extended-a-test-class-instance)) > 23
但是尝试这样做时,我遇到了正确调用方法a的问题:
(defparameter *test-instance* (make-instance 'test:a-test-class))
(defparameter *ext-test-instance* (make-instance 'exttest:extended-a-test-class))
(test:slot-a (test:method-a *test-instance*))
> 21
(test:slot-a (test:method-a *ext-test-instance*))
> 21
或者
(test:slot-a (exttest:method-a *test-instance*))
(test:slot-a (exttest:method-a *ext-test-instance*))
debugger invoked on a SIMPLE-ERROR in thread
#<THREAD "main thread" RUNNING {1002B03193}>:
There is no applicable method for the generic function
#<STANDARD-GENERIC-FUNCTION EXTTEST:METHOD-A (1)>
when called with arguments
(#<TEST:A-TEST-CLASS {10041148A3}>)
两者都不是真正为我工作,因为无论哪种方式我都无法编译,或者该方法的效果不如预期。如果类和方法定义在同一个包中,那么一切正常。
因此:如何在实例上调用方法而不需要处理相应的包? (如果我不能这样做,我想知道我对 Common-Lisp 中的 OO 编程的期望是如何被误导的)
对于我想要的输出的“工作”示例,我编写了这个 c++ 程序。我确实知道 CLOS 的工作方式与“常见的”面向对象系统不同,因为方法不“属于”类。但我希望任何面向对象的系统(以某种方式)能够像这样表现/使用:
#include <iostream>
namespace test {
class sub {
public:
virtual sub* method_a() = 0;
};
class a_test_class : public sub
{
protected:
int value;
public:
a_test_class(int val) : value(val) {
}
a_test_class* method_a() {
value = 21;
return this;
}
int get_value() {
return value;
}
};
}
namespace exttest {
class extended_a_test_class : public test::a_test_class {
public:
extended_a_test_class(int val) : a_test_class(val) { }
extended_a_test_class* method_a() {
std::cout << "calling overloaded method" << std::endl;
this->value = 23;
return this;
}
};
}
int main(int argc,const char* argv[]) {
test::a_test_class* atc = new test::a_test_class(42);
test::a_test_class* eatc = new exttest::extended_a_test_class(42);
std::cout << atc->method_a()->get_value() << std::endl;
std::cout << eatc->method_a()->get_value() << std::endl;
delete atc;
delete eatc;
}
> ./a.out
21
calling overloaded method
23