I'm trying to overload operator<<. When trying I got an error saying
Error: Passing const as this argument discards qualifiers
So I added const to my functions but now I'm getting this error:
Binding reference of type .. to const.
Main.cpp
ostream& operator<<(ostream& ostr, const Student& stud){
float mo = 0;
int quantity = stud.get_grade().size();\
.
.
.
Get_grade Function
vector<pair<Subject *, float>>& Student::get_grade() const{
return grade;
}
Error
binding reference of type ‘std::vector<std::pair<Subject*, float> >&’ to ‘const std::vector<std::pair<Subject*, float> >’ discards qualifiers
| return grade;
Grade is a vector
CodePudding user response:
get_grade
is a const member function meaning that the type of this
pointer inside it is const Student*
which in turn means that the data member grade
is treated as if it were itself const
. But the problem is that the return type of your function is an lvalue reference to non-const std::vector
meaning it cannot be bound to a const std::vector
.
To solve this just add a low-level const
in the return type of the function as shown below:
vvvvv------------------------------------------------------------->low-level const added
const vector<pair<Subject *, float>>& Student::get_grade() const{
return grade;
}