我有这个中介模式:
档案actor.hpp
#pragma once
#include <memory>
#include "mediator.hpp"
class actor : std::shared_from_this<actor>
{
public:
actor(std::shared_ptr<mediator> mediator) : mediator_(mediator)
{
}
virtual ~actor() = 0;
virtual void changed()
{
mediator_->actor_changed(std::make_shared<actor>(this));
}
private:
std::shared_ptr<mediator> mediator_;
};
档案mediator.hpp
#pragma once
#include <memory>
class actor;
class mediator : public std::shared_from_this<mediator>
{
public:
virtual ~mediator() = 0;
virtual void actor_changed(std::shared_ptr<actor> actor) = 0;
}
演员request_handler.hpp
#pragma once
#include "actor.hpp"
class request_handler : public actor
{
public:
request_handler(std::shared_ptr<mediator> mediator) : actor(mediator)
{
}
void handle_request()
{
changed();
}
};
但我收到错误消息
actor.hpp:16 error: invalid new-expression of abstract class type 'actor'
因为我无法实现抽象类的实例化。但这样做的正确方法是什么?
答案 0 :(得分:4)
此代码:
mediator_->actor_changed(std::make_shared<actor>(this));
在逻辑上等于:
auto ptr = std::shared_ptr<actor>( new actor( this ) );
mediator_->actor_changed(ptr);
这很可能不是你想要的,所以你需要拨打shared_from_this()来代替:
mediator_->actor_changed( this->shared_from_this() );
您需要继承的和类称为std::enable_shared_from_this而不是shared_from_this