简体   繁体   中英

Error: Binding reference of type .. to const

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

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM