使用如下所示的类和派生,有没有办法让基类方法返回派生类型的对象引用而不是它自己的类型,所以语法上我可以将方法链接在一起?
假设对象A
包含方法a1,a2
,衍生AD
添加方法ad1
如何制作AD_instance.a1().a2().ad1();
的有效方法链?
下面是两个有问题的课程。忽略它实际做的事情,方法链是唯一重要的部分。
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();
答案 0 :(得分:1)
您可以在派生类中创建一个合适的重载,该派生调度到基类版本但返回自身的对象:
class workerA {
// ...
workerA& Start() {
this->AsyncWorker::Start();
return *this;
}
workerA& Detach() {
this->AsyncWorker::Detach();
return *this;
}
// ...
};
答案 1 :(得分:0)
希望这会让你的问题更加清晰。
#include <iostream>
struct Base
{
virtual Base& foo() = 0;
};
struct Derived : Base
{
virtual Derived& foo()
{
std::cout << "Came to Derived::foo()\n";
return *this;
}
void bar()
{
std::cout << "Came to Derived::bar()\n";
}
};
int main()
{
Derived derived;
derived.foo().bar(); // OK. From the interface of Derived, foo()
// returns a Derived&.
Base& base = derived;
base.foo().bar(); // Not OK. From the interface of Base, foo()
// returns a Base&.
return 0;
}