在这个项目中,我使用QList
来存储名为RespirationTest
的类的实例。 使用动态内存时,访问RespirationTest
成员很容易,但由于我将QLIST
切换为指针,因此出现了问题
//class declaration
class RespirationTest: public QListWidgetItem
{
public:
RespirationTest();
~RespirationTest();
public slots:
double GetAmplitude() { return _amplitude; }
private:
double _amplitude;
}
当我试图访问我的QLIST
对象的成员时(当RespTest
是QLIST
时使用),出现了问题
//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'
}
快速修复:改用.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();