繁体   English   中英

对象具有与成员函数 C++ 不兼容的类型限定符

[英]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;
}

问题发生在a.display()下面的 ostream 运算符的实现中。 我不知道问题出在哪里,我有其他代码可以使用相同的实现。

错误信息:

对象具有与成员函数“sict::Course::display”不兼容的类型限定符,对象类型是 const sict::Course

operator<<() , a.display(); 失败,因为a被声明为const 您不能在其上调用非常量成员函数。

Course::display()应该被声明为 const 成员函数,它应该不会修改任何东西。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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