c++ - 使用 ide qt 在 C++ 中将 'const' 作为 'this' 参数传递时出错

标签 c++ qt

我正在使用 QtC++ 中开发一个应用程序,我有一个类: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/

相关文章:

c++ - QtConcurrent::map 和指针列表

python - 属性错误 : 'module' object has no attribute 'func' Only With C++ Invocation

c++ - Rust 更紧凑的列表初始化?

c++ - 大小写切换是这样工作的吗?

c++ - 为什么在声明派生类时需要将变量设置为基类中的某个值?

c++ - QPainter drawText 小数点

c++ - 一个 double 是否将方程中的每个 int 都提升为 double?

c++ - 为什么 QT 的 QList 方法与 std::list 兼容

c++ - 设计器中自定义小部件的 QT QIcon 属性

c++ - Qt:为什么 connect() 只在主窗口类中起作用?