我有一个基类 (Notification) 和两个子类 (WebNotification 和 DesktopNotification)。我从外部源接收 WebNotifications 和 DesktopNotifications,然后将它们作为通知指针传递给 GUI 实体,该实体应该根据通知类型执行不同的操作。 如何根据 Notification* 推断子类型?
我知道将类型为 Notification 的枚举添加到 Notification 类中会起作用,但这似乎不是一个优雅的解决方案。
我有其他选择吗?
最佳答案
可能有多种选择。
首先,专门化的行为应该是类的一部分,而不是客户端的一部分。这意味着您应该避免动态检查类的类型,除非您真的被迫这样做。
这通常是通过多态来实现的:
class Notification {
public:
virtual void render(UI* ui) = 0;
};
class WebNotification : public Notification {
public:
void render(UI* ui) override {
....
}
};
在某些情况下这还不够,例如您可以选择标记您的类
class Notification {
public:
enum class Type {
WEB,
DESKTOP
};
private:
Type type;
protected:
Notification(Type type) : type(type) { }
public:
Type getType() const { return type; }
};
class WebNotification : public Notification {
public:
WebNotification() : Notification(Notification::Type::WEB) { }
};
...
Notification* notification = ...
if (notification->getType() == Notification::Type::WEB)
...
或者让编译器为您标记它们,但您必须启用 RTTI,有时这是不可取的:
if (dynamic_cast<WebNotification*>(notification) != null) {
...
}
关于c++ - 如何从基指针推断类的子类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32655908/