简体   繁体   English

重载 << 运算符时如何解决此错误消息

[英]How do I solve this error message when overloading the << operator

when I try to overload the << operator I get the error "too many parameters for this operator function"?当我尝试重载 << 运算符时,出现错误“此运算符函数的参数过多”?

This is the code I have written:这是我写的代码:

class studentrecord{
string firstname, lastname, grade;        
studentrecord(string firstname, string lastname, string grade){
    this -> firstname = firstname;
    this -> lastname = lastname;
    this -> grade = grade;
}

ostream& operator<<(ostream& os, const studentrecord& studentrecord) {
    os << "\n\t" << studentrecord.firstname << "\t" << studentrecord.lastname << "\t" << studentrecord.grade;
    return os;
}
};

Thanks for the help!谢谢您的帮助!

@DesmondGold pointed out the answer, just use the "friend" keyword. @DesmondGold 指出了答案,只需使用“朋友”关键字即可。

The proper use of this function can be seen on this page:这个function的正确使用可以看这个页面:

Overloading the << Operator for Your Own Classes 为你自己的类重载 << 运算符

The code becomes:代码变为:

class studentrecord{
string firstname, lastname, grade;        
studentrecord(string firstname, string lastname, string grade){
    this -> firstname = firstname;
    this -> lastname = lastname;
    this -> grade = grade;
}

friend ostream& operator<<(ostream& os, const studentrecord& studentrecord) {
    os << "\n\t" << studentrecord.firstname << "\t" << studentrecord.lastname << "\t" << studentrecord.grade;
    return os;
}
};

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

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