问题描述
假定QOpenGLFunctions
对象是类的成员.由于gl*
方法未在适当的地方标记为 const ,因此即使它们可能根本不进行状态更改,也无法在 const 方法中调用它们.
Assume a QOpenGLFunctions
object is a member of a class. Since the gl*
methods are not marked const where appropriate, they cannot be invoked in a const method even if they may make no state changes at all.
我使用QOpenGLFunctions
是错误的吗?
推荐答案
虽然有点哲学,但我可以说您使用它是错误的".通过使QOpenGLFunctions
成为您的类的成员,您是在说OpenGL函数是您的类状态的一部分.他们真的不是.它们是您的课程使用的,但它们不是您的课程的一部分.
It's somewhat philosophical, but I could argue that you're using it "wrong". By making QOpenGLFunctions
a member of your class, you're saying that the OpenGL functions are part of your class state. Which they are really not. They are something your class uses, but they are not part of your class.
您可以通过以下几种方法来解决此问题:
You have a couple of options to fix this:
- 您可以在成员定义(
mutable QOpenGLFunctions m_...
)中添加mutable
. - 您可以使成员变量成为指向
OpenGLFunctions
的指针,并在类的构造函数中分配该对象.
- You can add a
mutable
to the member definition (mutable QOpenGLFunctions m_...
). - You can make the member variable a pointer to
OpenGLFunctions
, and allocated the object in the constructor of your class.
使用mutable
总是让我感到有些不舒服,即使它有合法用途.在这种情况下,我显然更喜欢选项2.除了解决您的const-correctity问题以外,它还表示您的类与OpenGLFunctions
之间的较弱耦合确实与我在引言中解释的正确关系相匹配.
Using mutable
always feels kind of hacky to me, even though it has legitimate uses. I clearly prefer option 2 in this case. Beyond solving your const-correctness problem, it also expresses the weaker coupling between your class and OpenGLFunctions
that really matches the correct relationship I explained in the introduction.
这篇关于QOpenGLFunction不是const正确的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!