2016-08-05 151 views
0
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运算符时发生问题。 我没有看到问题出在哪里,我有其他代码与相同的实现工作。对象具有与成员函数C++不兼容的类型限定符

错误消息:

该对象具有键入不与成员函数“SICT ::课程::显示”对象类型兼容限定符是常量SICT ::场

+0

的可能重复的[链接](http://stackoverflow.com/questions/24677032/object-has-type-qualifiers-that-are-not-compatible-with-the-member-function) –

+2

'Course :: display'函数,为什么硬编码写入'std :: cout'?如果你想写一个文件(这可能会导致你的'operator <<'超载),该怎么办? –

回答

4

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

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

void Course::display() const { 
         ~~~~~ 
    ... 
} 
相关问题