c++ - QList方法at()与[]的区别
天蓬老师
天蓬老师 2017-04-17 13:30:52
0
2
582

代码如下:

QList<QVariant> *list;
    for(int i=startrow;i<rowcount+1;i++)
    {
        list=axExcel1.GetSelectSheetOneRowDate(1,i,startcolumn,startcolumn+columncount-1);
        int len=list->length();
        for(int j=0;j<len;j++)
        {
            qDebug()<<list->at(j);
        }
        delete list;list=NULL;
    }

其中

axExcel1.GetSelectSheetOneRowDate(1,i,startcolumn,startcolumn+columncount-1)

返回一个QList<QVariant>*指针,我用list去接收这个指针,然后解析list。
当我使用at()时程序不会崩溃,但当我改为[]访问时如以下代码,程序在进入循环当j=1时在就会崩溃,请问这at()与[]有什么区别?为什么会崩溃?

 qDebug()<<list->[j];
 

错误提示如下:

Error - RtlWerpReportException failed with status code :-1073741823. Will try to launch the process directly

调试图片

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

모든 응답(2)
PHPzhong

[]和at语义差别不大,实现也是大同小异
来自qt官方的源码LINK

template <typename T>
inline const T &QList<T>::at(int i) const
{ 
    Q_ASSERT_X(i >= 0 && i < p.size(), "QList<T>::at", "index out of range");
     
    return reinterpret_cast<Node *>(p.at(i))->t(); 
}

template <typename T>
inline const T &QList<T>::operator[](int i) const
{ 
    Q_ASSERT_X(i >= 0 && i < p.size(), "QList<T>::operator[]", "index out of range");
    
    return reinterpret_cast<Node *>(p.at(i))->t(); 
}

template <typename T>
inline T &QList<T>::operator[](int i)
{ 
    Q_ASSERT_X(i >= 0 && i < p.size(), "QList<T>::operator[]", "index out of range");
    detach(); // 这里多了一步 !! 
    return reinterpret_cast<Node *>(p.at(i))->t(); 
}
刘奇

区别就是at进行了越界检查,[]没有

최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!