将派生类作为参数传递给方法,该方法是具有智能指针的基类

Passing derived class to method as argument which is base class with smart pointer

本文关键字:方法 智能 基类 指针 派生 参数传递      更新时间:2023-10-16

我最近读过Head First Design Pattern。这本书展示了Java中的相关代码。然而,我尝试将Java代码转换为C++。在观察者模式章节,我在某个地方转换时被卡住了。相关代码如下。

class Subject{ //Publisher
public:
virtual void registerObserver(ObserverPtr o) = 0;
virtual void removeObserver(ObserverPtr o) = 0;
virtual void notifyObservers() = 0;
};
using SubjectPtr = std::shared_ptr<Subject>;

用户类接口:

class Observer{
public:
virtual void update(double temp, double humidity, double pressure) = 0;
};
using ObserverPtr = std::shared_ptr<Observer>;

显示元素界面:

class DisplayElement{
public:
virtual void display() = 0;
};
using DisplayElementPtr = std::shared_ptr<DisplayElement>;

和当前条件显示

class CurrentConditionsDisplay : public Observer, public DisplayElement{
SubjectPtr m_weatherData;
double temperature;
double humidity;
public:
CurrentConditionsDisplay(SubjectPtr weatherData);
void update(double temperature, double humidity, double pressure);
void display();
};
using CurrentConditionsDisplayPtr = std::shared_ptr<CurrentConditionsDisplay>;

我的问题:

在CurrentCurrentConditionsDisplay类的构造函数中,我希望Publisher(Subject(注册CurrentCurrentConditions Display。

//constructor
CurrentConditionsDisplay::CurrentConditionsDisplay(SubjectPtr weatherData) :
temperature(0),
humidity(0)
{
m_weatherData = weatherData;
/* How should I pass 'this' ? */
m_weatherData->registerObserver(???????); //parameter type is ObserverPtr.
}

由于参数类型为ObserverPtr,应如何传递"pointer this">

我建议工厂方法,比如:

std::shared_ptr<CurrentConditionsDisplay>
MakeCurrentConditionsDisplay(SubjectPtr weatherData)
{
auto res = std::make_shared<CurrentConditionsDisplay>(weatherData);
weatherData->registerObserver(res);
return res;
}

如果你坚持在构造函数中这样做,你可能会使用std::enable_shared_from_this:

class CurrentConditionsDisplay :
public std::enable_shared_from_this<CurrentConditionsDisplay>,
public Observer,
public DisplayElement
{
SubjectPtr m_weatherData;
double temperature = 0;
double humidity = 0;
public:
explicit CurrentConditionsDisplay(SubjectPtr weatherData) :
m_weatherData(weatherData)
{
m_weatherData->registerObserver(shared_from_this());
}
void update(double temperature, double humidity, double pressure) override;
void display() override;
};

std::shared_from_this无法从构造函数调用