[英]Accessing members of a class QList Pointer
I have this project where I use a QList
to store instances of a class called RespirationTest
.我有这个项目,我使用
QList
来存储名为RespirationTest
的 class 的实例。 Accessing RespirationTest
members is easy when using dynamic memory, but I am having trouble since I switched my QList
for a pointer使用动态 memory 时访问
RespirationTest
成员很容易,但我遇到了麻烦,因为我将QList
切换为指针
//class declaration
class RespirationTest: public QListWidgetItem
{
public:
RespirationTest();
~RespirationTest();
public slots:
double GetAmplitude() { return _amplitude; }
private:
double _amplitude;
}
Problem is here, when I try to access members of my QList
objects (used to work when respTest
was a QList
)问题就在这里,当我尝试访问我的
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'
}
Quick fix: Use .at(int idx)
instead:快速修复:使用
.at(int idx)
代替:
qDebug() << "ampl" << i << ": " << respTests->at(i).GetAmplitude();
The problem with using operator[]
is that you access the memory of the pointer instead of accessing the underlying QList
:使用
operator[]
的问题是您访问指针的 memory 而不是访问底层QList
:
respTests[i] // returns the QList<> instance at `i` instead
// of a `RespirationTest` object
So if you want to keep using []
, you will need to further access the i
th element by using []
or .at()
:因此,如果您想继续使用
[]
,则需要使用[]
或.at()
进一步访问第i
个元素:
qDebug() << "ampl" << i << ": " << respTests[0].at(i).GetAmplitude();
I highly recommend using .at()
if you really have to do this.如果您真的必须这样做,我强烈建议您使用
.at()
。 Otherwise just don't use pointers at all as it's over-complicating the problem and may leak memory.否则根本不要使用指针,因为它会使问题过于复杂,并且可能会泄漏 memory。 Furthermore, avoid
QList<>
, use QVector
instead.此外,避免
QList<>
,使用QVector
代替。
since respTests
is a pointer you need to use ->
instead of .
因为
respTests
是您需要使用的指针->
而不是.
qDebug() << "object at " << i << ": " << respTests->at(i).GetAmplitude();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.