![](/img/trans.png)
[英]C++ const "and the object has type qualifiers that are not compatible with the member
[英]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.