gpt4 book ai didi

指向从未成为 const 的 const 对象的 C++ 指针

转载 作者:行者123 更新时间:2023-11-30 03:35:13 25 4
gpt4 key购买 nike

<分区>

我有一组学生和一个迭代器,它可以找到我需要更改的特定学生。问题是,当我去更改指针指向的对象时,它说该对象是常量。我不确定这是为什么,因为我认为我从来没有明确地使对象保持不变。我是 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);

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com