我正在使用 Qt
在 C++
中开发一个应用程序,我有一个类:AnimationMasse
class AnimationMasse
{
public:
int etat ;
double x ;
double y ;
public:
AnimationMasse();
void setx(double XX);
};
AnimationMasse::AnimationMasse()
{
etat = 0 ;
x = -0.54 ;
y = -0.2 ;
}
void AnimationMasse::setx(double XX){
x = x+XX;
}
我创建了一个对象:
QVector <AnimationMasse> Masse;
AnimationMasse x ;
Masse.append(x) ;
问题是:如果我这样做:
ui->animation->Masse.at(0).setx(1);
在我看来,错误:
error: passing 'const AnimationMasse' as 'this' argument of 'void AnimationMasse::setx(double)' discards qualifiers [-fpermissive]
ui->animation->Masse.at(0).setx(1);
谁解决了这个问题?
最佳答案
如您在 Qt 文档中所见 http://doc.qt.io/qt-5/qvector.html#at函数 at
返回常量引用,所以你不能调用 setx(1)
。在这种情况下,您可以使用 QVector
类的 operator[]:
T & operator[](int i)
简单的例子:
#include "QCoreApplication"
#include "QVector"
#include "QtDebug"
class AnimationMasse
{
private:
int etat ;
double x ;
double y ;
public:
AnimationMasse()
: etat(0)
, x(-0.54)
, y(-0.2)
{
}
double getx(){return x;}
void setx(double XX){ x += XX; }
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QVector <AnimationMasse> Masse;
AnimationMasse x;
Masse.append(x);
qDebug() << Masse[0].getx();
Masse[0].setx(1);
qDebug() << Masse[0].getx();
return a.exec();
}
关于c++ - 使用 ide qt 在 C++ 中将 'const' 作为 'this' 参数传递时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37453190/