簡體   English   中英

訪問 class QList 指針的成員

[英]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對象的成員時(當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'
}

快速修復:使用.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM