簡體   English   中英

列表錯誤的C ++迭代器

[英]C++ iterator on a list error

我在C ++類中具有以下內容:我想通過調用isValid()檢查迭代器是否仍然有效之后,通過調用getNextQuestion()函數來一次使用迭代器來獲取問題列表的元素。 它給了我以下可怕的錯誤:

passing ‘const iterator {aka const std::_List_iterator<domain::Question>}’ as ‘this’ argument of ‘std::_List_iterator<_Tp>::_Self& 
std::_List_iterator<_Tp>::operator++() [with _Tp = domain::Question,std::_List_iterator<_Tp>::_Self = 
std::_List_iterator<domain::Question>]’ discards qualifiers [-fpermissive]

#ifndef TESTREPOSITORY_H_
#define TESTREPOSITORY_H_

#include <iostream>
#include <iterator>
#include <list>
#include <algorithm>
#include <fstream>
#include "../domain/question.h"

using namespace domain;

namespace repository{
template<class T>
class TestRepository{
std::string file;
std::list<T> questions;
typename std::list<T>::iterator it;
public:
TestRepository(std::string& file=""):file(file){
    this->questions = this->getQ();
    this->it = this->questions.begin();
};

std::list<T> getQ() const{
    std::list<T> listq;
    using namespace std;
    string line;
    std::ifstream fin(file.c_str());
    while(fin.good()){
        Question q;
        fin >> q;
        listq.push_back(q);
    }
    fin.close();
    return listq;
}

const bool isValid() const{
    return this->it != this->questions.end();
}

const T getNextQuestion() const{
    T q = (*this->it);
    ++this->it;
    return q;
}

};
}

#endif /* TESTREPOSITORY_H_ */

這是我稱為這些功能的代碼,也許這是來自以下方面的問題:

#include "TestController.h"
#include "../domain/test.h"
#include <iostream>
#include <list>
#include <iterator>

 namespace controller{

TestController::TestController(repository::TestRepository<domain::Question>* repo,int   testId){
this->repo = repo;
this->testId = 0;
}

const test TestController::getCurrentTest() const{
test test(this->testId,0,0);
return test;
}

const bool TestController::isValid() const{
return this->repo->isValid();
 }

const Question TestController::getNextQuestion() const{
return this->repo->getNextQuestion();
}



}

這里:

const T getNextQuestion() const{
    T q = (*this->it);
    ++this->it;
    return q;
}

您正在更改字段it並且不應該這樣做,因為方法是const 如果僅在未修改“存儲庫”的意義上使用const ,但其內部迭代器無關緊要,則可以使用mutable關鍵字:

mutable typename std::list<T>::iterator it;

您正在嘗試修改const成員函數中的成員,這是被禁止的(那是const成員函數的要點):

const T getNextQuestion() const{
    T q = (*this->it);
    ++this->it;   // << Here
    return q;
}

此方法應為非const,或考慮使成員迭代器mutable

mutable typename std::list<T>::iterator it;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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