c++ - 抽象基类的 QPointer

标签 c++ qt pointers qpointer

我正在编写一个表达式解析库。 它是用Qt写的,我有这样一个类结构:
QCExpressionNode-表达式所有部分的抽象基类
QCConstantNode-表达式中的常量(扩展QCExpressionNode)
QCVariableNode-表达式中的变量(扩展QCExpressionNode)
QCBinaryOperatorNode-二进制加法、减法、乘法、除法和幂运算符(扩展QCExpressionNode)

我希望能够使用智能指针(如 QPointerQSharedPointer),但我遇到了以下挑战:
- QPointer 可以与抽象类一起使用吗?如果是,请提供示例。
- 如何将 QPointer 转换为具体的子类?

最佳答案

我看不出有任何你不能这样做的理由。举个例子:

class Parent : public QObject
{
public:
   virtual void AbstractMethod() = 0;
};

class Child: public Parent
{
public:
   virtual void AbstractMethod() {  }

   QString PrintMessage() { return "This is really the Child Class"; }
};

现在像这样初始化一个 QPointer:

QPointer<Parent> pointer = new Child();

然后您可以像通常使用 QPointer 一样调用“抽象”类上的方法

pointer->AbstractMethod();

理想情况下这就足够了,因为您可以使用父类中定义的抽象方法访问所需的一切。

但是,如果您确实需要区分您的子类或使用仅存在于子类中的东西,您可以使用 dynamic_cast。

Child *_ChildInstance = dynamic_cast<Child *>(pointer.data());

// If _ChildInstance is NULL then pointer does not contain a Child
// but something else that inherits from Parent
if (_ChildInstance != NULL)
{
   // Call stuff in your child class
   _ChildInstance->PrintMessage();
}

希望对您有所帮助。

额外注意:您还应该检查 pointer.isNull() 以确保 QPointer 实际上包含某些内容。

关于c++ - 抽象基类的 QPointer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5657269/

相关文章:

c++ - 在 C++ 中隐藏 namespace

c++ - 在 lambda 中使用未捕获的变量

c++ - 从 C++ 对象返回一个 malloc 指针

c++ - 通过 OpenGL 进行图像缩放(KeepAspectRatioByExpanding)

c - 当我尝试在字符指针数组中输入字符串时,为什么 scanf 不起作用?

php - 为什么我必须在函数调用中使用引用运算符 (&)?

c++ - map 数据结构不显示 main.cpp 中保存的条目

c++ - Cpp Friend 函数无法访问私有(private)静态成员

c++ - 如何实现订阅数据提要?通知对象

c++ - CMake 错过 Qt5 的 QT_DEFINITIONS 变量