抽象基类的 QPointer
我正在编写一个表达式解析库。 它是用 Qt 编写的,我有一个这样的类结构:QCExpressionNode
- 表达式所有部分的抽象基类QCConstantNode
- 表达式中的常量(扩展 QCExpressionNode
)QCVariableNode
- 表达式中的变量(扩展 QCExpressionNode
)QCBinaryOperatorNode
-二进制加法、减法、乘法、除法和幂运算符(扩展QCExpressionNode
)
我希望能够使用智能指针(例如QPointer 或
QSharedPointer
),但我遇到了以下挑战:
-QPointer
可以与抽象类一起使用吗?如果是,请提供示例。
-如何将QPointer
转换为具体的子类?
I am writing an expression-parsing library.
It is written with Qt, and I have a class structure like this:QCExpressionNode
-Abstract Base Class for all pieces of an expressionQCConstantNode
-Constants in an expression (extends QCExpressionNode
)QCVariableNode
-Variables in an expression (extends QCExpressionNode
)QCBinaryOperatorNode
-Binary Addition, Subtraction, Multiplication, Division and Power operators (extends QCExpressionNode
)
I would like to be able to use smart pointers (like QPointer
or QSharedPointer
), but I am running into the following challenges:
-Can a QPointer
be used with abstract classes? If so, please provide examples.
-How to cast a QPointer
to a concrete subclass?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不明白你有什么理由不能这样做。举个例子:
现在像这样初始化一个 QPointer:
然后你可以像通常使用 QPointer 一样调用“抽象”类上的方法
理想情况下,这就足够了,因为你可以使用你的抽象方法中定义的抽象方法来访问你需要的所有内容。父类。
但是,如果您确实需要区分子类或使用仅存在于子类中的内容,则可以使用dynamic_cast。
我希望这有帮助。
额外注意:您还应该检查pointer.isNull()以确保QPointer确实包含某些内容。
I don't see any reason why you can't do this. Take this example:
Now initialize a QPointer like this:
You can then call methods on the 'abstract' class as you would normally with a QPointer
Ideally this would be enough, because you could just access everything you need with the abstract methods defined in your parent class.
However, if you really need to differentiate between your child classes or use something that only exists in the child class, you can use dynamic_cast.
I hope that helps.
Extra note: You should also check pointer.isNull() to make sure that the QPointer actually contains something.