将派生类作为参数传递给方法,该方法是具有智能指针的基类
Passing derived class to method as argument which is base class with smart pointer
我最近读过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
无法从构造函数调用
相关文章:
- 对于C++中使用智能指针的指针算术限制,有没有一种变通方法
- 初始化指向类实例的智能指针并访问其方法
- 构造智能点数据类型以及普通数据类型的通用方法
- 类的方法和对象。参考?智能指针?简单的初始化?
- 将派生类作为参数传递给方法,该方法是具有智能指针的基类
- 从ostringstream获取最长行的字符数的智能方法
- 使用push_back方法获取智能指针矢量时应用崩溃
- 有没有更好的方法来添加两个智能指针?
- 从类成员返回智能指针的正确方法?
- 将对象附加到智能指针向量的最佳方法
- 使用删除与智能指针释放内存以及释放内存的正确方法
- 为什么我的COM智能指针从方法返回时会被删除
- 将从方法返回的原始指针存储到智能指针中
- 使用智能指针将右值引用绑定到抽象类的替代方法
- 为性能库制作高效包装器的智能方法
- 如何使用智能指针调用包装对象的方法
- 测试类型是否为(智能)指针的通用方法
- 在C++中使用智能指针分配和删除内存的有效方法
- 初始化智能指针成员变量的正确方法是什么
- C++方法在简单的C++项目中运行良好,但在智能设备项目中则不然