提问者:小点点

访问类QList指针的成员


在这个项目中,我使用QList来存储名为RespirationTest的类的实例。 使用动态内存时,访问RespirationTest成员很容易,但由于我将QLIST切换为指针,因此出现了问题

//class declaration

class RespirationTest: public QListWidgetItem
{

public:
    RespirationTest();
    ~RespirationTest();

public slots:
double GetAmplitude() { return _amplitude; }

private:
double _amplitude;
}

当我试图访问我的QLIST对象的成员时(当RespTestQLIST时使用),出现了问题

//MainWindow

QList<RespirationTest> * respTests;

respTests = new QList<RespirationTest>;

void MainWindow::on_load_button_clicked()
{
RespirationTest *currTest = new RespirationTest;
respTests->push_back(*currTest);
qDebug() << "ampl" << i << ": " << respTests[i].GetAmplitude(); // no member named 'GetAmplitude'
}

共2个答案

匿名用户

快速修复:改用.at(int idx):

qDebug() << "ampl" << i << ": " << respTests->at(i).GetAmplitude();

使用operator[]的问题是访问指针的内存,而不是访问底层的QList:

respTests[i] // returns the QList<> instance at `i` instead
             // of a `RespirationTest` object

因此,如果希望继续使用[],则需要使用[].at():

qDebug() << "ampl" << i << ": " << respTests[0].at(i).GetAmplitude();

如果确实必须这样做,我强烈建议您使用.at()。 否则,根本不要使用指针,因为这会使问题过于复杂,并且可能会泄漏内存。 此外,避免qlist<>,而是使用qvector

匿名用户

由于resptests是一个指针,您需要使用->而不是

qDebug() << "object at " << i << ": " << respTests->at(i).GetAmplitude();