好的,我正在为一所学校的项目工作,我们需要在另一个类中有一个类的链表(一个名为“objective”的类中的类“task”的链表),所以对于我正在使用STL课程。现在我几乎设置它,但在我的显示功能中,为了显示任务的内容,我正在使用迭代器。但是我无法将taskList.begin()分配给迭代器,因为它给了我一个错误。
以下是我认为相关的代码。
objective.h
#ifndef OBJECTIVE_H
#define OBJECTIVE_H
#include <string>
#include <list>
#include "date.h"
#include "task.h"
using namespace std;
namespace team2
{
class objective
{
private:
string objective_name, objective_desc, resources[10];
int category, priority, res_used;
double time;
date start, end;
int status;
std::list<task> taskList;
public:
// CONSTRUCTORS
objective();
objective(string objN, string objD, int c, int p, date s, date e, double t, string res[], int resU, int stat, list<task>& tList);
...
// CONSTANT MEMBER FUNCTIONS
void display() const;
...
};
}
#endif
objective.cpp(这是我收到错误的地方)
#include "objective.h"
#include "date.h"
#include <cstdlib>
#include <cassert>
#include <string>
#include <list>
#include "task.h"
using namespace std;
namespace team2
{
void objective::display() const // display() - Displays the complete contents of a single objective
{
int days, hours, minutes;
std::list<task>::iterator taskIterator;
days = floor(time/24.0); // Find the max number of days based off of the time (in hours)
hours = floor(time - days*24); // Find the max number of hours after deduction of days
minutes = floor((time - (days*24 + hours))*60); // Find the number or minutes after taking into account hours and days
cout << "\nObjective Name: " << objective_name << endl;
cout << "Objective Description: " << objective_desc << endl;
cout << "Category: Quad " << category << endl;
cout << "Priority: " << priority << endl;
cout << "Starting Date: " << start.getMonth() << "/" << start.getDay() << "/" << start.getYear() << endl;
cout << "Ending Date: " << end.getMonth() << "/" << end.getDay() << "/" << end.getYear() << endl;
cout << "Time Required: " << days << " Days " << hours << " Hours " << minutes << " Minutes " << endl;
cout << "Resources: " << endl;
if(res_used == 0)
cout << "\tNo Resources" << endl;
for(int i = 0; i < res_used; i++)
cout << "\t" << resources [i] << endl;
cout << "Current Status: ";
if(status == 1)
cout << "Completed" << endl;
else if(status == 0)
cout << "Incomplete" << endl;
cout << "Tasks: " << endl;
if(taskList.empty())
cout << "\tNo Resources" << endl;
for(taskIterator = taskList.begin(); taskIterator != taskList.end(); taskIterator++)
{
(*taskIterator).display();
cout << endl;
}
}
}
任务类几乎与目标类相同,省略了一些字段。 for循环中发生错误。 for(taskIterator = taskList.begin(); ...)任何人都知道问题的原因?如有必要,我还可以提供更多代码。提前谢谢!
答案 0 :(得分:4)
该方法为const
,taskList
是成员,因此您不能在其上使用非const
迭代器。
使成员方法const
是一个合同,该方法不会更改非mutable
类成员,也不会调用非const
成员方法。通过使用非const
迭代器,您就违反了该合同。
由于display
是const,因此可以使用const迭代器:
std::list<task>::const_iterator taskIterator;