简体   繁体   中英

The object has type qualifiers that are not compatible with the member function C++

std::ostream& operator<<(std::ostream&, const Course&);

void Course::display() {
    std::cout << std::left << courseCode_ << " | " << std::setw(20) << courseTitle_ << " | " << std::right
        << std::setw(6) << credits_ << " | " << std::setw(4) << studyLoad_ << " | ";
}

std::ostream& operator<<(std::ostream& os, const Course& a) {
    a.display();
    return os;
}

Problem occurs at the implementation of the ostream operator below a.display() . I don't see where the problem is, I have other codes that work with the same implementation.

error message:

The object has type qualifiers that are not compatible with the member function "sict::Course::display" object type is const sict::Course

In operator<<() , a.display(); fails because a is declared as const . You can't call non-const member function on it.

Course::display() should be declared as const member function, it's supposed to not modify anything.

void Course::display() const {
//                     ^^^^^
    ...
}

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