[英]Accessing members of a class QList Pointer
我有这个项目,我使用QList
来存储名为RespirationTest
的 class 的实例。 使用动态 memory 时访问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[]
的问题是您访问指针的 memory 而不是访问底层QList
:
respTests[i] // returns the QList<> instance at `i` instead
// of a `RespirationTest` object
因此,如果您想继续使用[]
,则需要使用[]
或.at()
进一步访问第i
个元素:
qDebug() << "ampl" << i << ": " << respTests[0].at(i).GetAmplitude();
如果您真的必须这样做,我强烈建议您使用.at()
。 否则根本不要使用指针,因为它会使问题过于复杂,并且可能会泄漏 memory。 此外,避免QList<>
,使用QVector
代替。
因为respTests
是您需要使用的指针->
而不是.
qDebug() << "object at " << i << ": " << respTests->at(i).GetAmplitude();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.