方法调用基类方法后链接派生类方法 [英] method chain a derived class method after calling a base class method
问题描述
具有如下所示的类和派生类,基类方法是否有办法返回派生类型而不是其自身类型的对象引用,因此从语法上讲,我可以将这些方法链接在一起?
With a class and a derivative as shown below, is there a way for the base classes methods to return a object reference of the derived type instead of its own type so syntactically i can chain the methods together?
假设对象 A
具有方法 a1,a2
,而派生的 AD
添加了方法 ad1
去制作一个有效的方法链 AD_instance.a1().a2().ad1();
?
Suppose that object A
has methods a1,a2
and derivative AD
adds a method ad1
how would one go about making a valid method chain of AD_instance.a1().a2().ad1();
?
下面是有问题的两个类.忽略它的实际作用,方法链接是唯一重要的部分.
Below are the two classes in question. Ignoring what it's actually doing, the method chaining is the only important part.
class AsyncWorker() {
pthread_t worker;
public:
AsyncWorker();
void *worker_run();
AsyncWorker& Detach() { /*code*/ return *this; }
AsyncWorker& Start() {
pthread_create(&worker, NULL, &AsyncWorker::worker_helper, this);
return *this;
}
static void *worker_helper(void *context) {
return ((AsyncWorker *)context)->worker_run();
}
};
class workerA : public AsyncWorker {
public:
int a;
workerA(int i) { a = i; }
void* worker_run() { ++a; sleep(1); }
workerA& other_method_i_want_to_chain() { return *this };
};
像这样被束缚.
workerA A(0);
A.Start().Detach().other_method_i_want_to_chain();
推荐答案
您可以在派生类中创建合适的重载,该重载分派到基类版本,但返回其自身的对象:
You could create a suitable overload in your derived class which dispatches to the base class version but return an object of itself:
class workerA {
// ...
workerA& Start() {
this->AsyncWorker::Start();
return *this;
}
workerA& Detach() {
this->AsyncWorker::Detach();
return *this;
}
// ...
};
这篇关于方法调用基类方法后链接派生类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!