【问题标题】:The object has type qualifiers that are not compatible with the member function C++对象具有与成员函数 C++ 不兼容的类型限定符
【发布时间】:2016-12-11 08:50:53
【问题描述】:
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

【问题讨论】:

  • link的可能重复
  • Course::display 函数,为什么要硬编码写入std::cout?如果您想写入文件怎么办(这可能与您拥有的 operator&lt;&lt; 重载有关)?

标签: c++ operator-overloading iostream member-functions


【解决方案1】:

operator&lt;&lt;() 中,a.display(); 失败,因为 a 被声明为 const。你不能在它上面调用非常量成员函数。

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

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

【讨论】:

    猜你喜欢
    • 2014-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-06
    • 1970-01-01
    相关资源
    最近更新 更多