我在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();
}
}
答案 0 :(得分:1)
下面:
const T getNextQuestion() const{
T q = (*this->it);
++this->it;
return q;
}
您正在更改字段it
并且您不应该这样做,因为该方法是const
。如果您只想使用const
意味着您的&#34;存储库&#34;未修改,但其内部迭代器无关紧要,您可以使用mutable
关键字:
mutable typename std::list<T>::iterator it;
答案 1 :(得分:0)
您正在尝试修改const
成员函数中的成员,这是禁止的(这是const成员函数的重点):
const T getNextQuestion() const{
T q = (*this->it);
++this->it; // << Here
return q;
}
此方法应为非const,或者考虑让您的成员迭代器为mutable
:
mutable typename std::list<T>::iterator it;