【发布时间】:2017-01-03 02:56:24
【问题描述】:
我有一组学生和一个迭代器,它可以找到一个特定的学生,然后我需要对其进行更改。问题是,当我去更改指针指向的对象时,它说对象是 const。我不确定为什么会这样,因为我认为我从来没有明确地使对象保持不变。我对 C++ 比较陌生,所以我可能正在做一些事情来使 Student 对象意外地变为 const。
这里是主要功能
set<Student> students;
ifstream file(*somefilename*);
while (!file.is_open())
{
cout << filename << endl;
cout << "Could not open file. Enter new filename: ";
cin >> filename;
file.open(filename);
}
while (!file.eof()) {
string temp = "";
string name;
int regNo;
if (file.eof())break;
for (int i = 0; i < 3; i++) {
if (i == 0)
file >> regNo;
else {
file >> temp;
name += temp;
}
}
cout << "For loop done" << endl;
students.insert(Student(name, regNo));
}
file.close();
file.open("ex1/marks.txt");
while(!file.eof()){
int regNo;
string module;
int mark;
file >> regNo;
Student tempStud("",regNo);
file >> module;
file >> mark;
set<Student>::iterator it = students.find(tempStud);
if (it != students.end()) {
**it->addMark(module, mark);**//here's the problem code
}
}
file.close();
for (set<Student>::iterator it = students.begin(); it != students.end(); it++)
cout << *it << endl;
cin.get();}
这是Student类的头文件
public:
Student(const string &name, int regNo);
int getRegNo() const;
void addMark(string& module, float mark);
float getMark(const string &module) const;
float getMin() const;
float getMax() const;
float getAvg() const;
bool operator <(const Student& s2) const;
bool operator >(const Student& s2);
bool operator ==(const Student& s2);
private:
int regNo;
map<string, float> marks; // keys are modules, values are marks in range 0.0 to 100.0
friend ostream& operator<<(ostream &str, const Student &s);
【问题讨论】:
-
错误发生在哪一行?错误消息到底说了什么? (引用它)另外,请确保发布minimal 示例
-
它说 what 对象是 const?
-
Relevant question。其中的 MCVE 似乎是修改
std::set中元素的最佳方式。 -
Another relevant question,声明可变的。