重载<<运算符时提示“运算符函数参数过多”错误如何解决
错误原因
- 你将
operator<<重载函数定义为了类的成员函数,类的非静态成员函数会默认携带隐式的this指针作为第一个参数,你额外声明了两个参数ostream& os和const studentrecord&,总参数数量达到3个,而<<是二元运算符,仅允许2个参数,因此触发参数过多的报错。 - 由于
<<调用时左操作数是ostream类型的对象(比如cout),不是你自定义的studentrecord类对象,因此该运算符重载不能作为类的成员函数实现,必须定义为全局函数。 - 另外
studentrecord类的成员默认是私有访问权限,外部全局函数无法直接访问,需要做友元声明。
修正方案
推荐将operator<<声明为类的友元函数,修改后的代码如下:
#include <iostream> #include <string> // 若项目未使用using namespace std,需要给string、ostream添加std::前缀 using namespace std; class studentrecord{ private: string firstname, lastname, grade; public: studentrecord(string firstname, string lastname, string grade){ this->firstname = firstname; this->lastname = lastname; this->grade = grade; } // 添加friend关键字,声明该运算符重载为类的友元全局函数 friend ostream& operator<<(ostream& os, const studentrecord& record); }; // 运算符重载实现移到类外部 ostream& operator<<(ostream& os, const studentrecord& record) { os << "\n\t" << record.firstname << "\t" << record.lastname << "\t" << record.grade; return os; }
其他注意事项
- 不要给第二个参数命名为和类名完全相同的
studentrecord,容易和类名冲突,建议改为record之类的变量名 - 如果你不想使用友元,可以给类添加对应的
getFirstName()、getLastName()、getGrade()公有成员函数,在operator<<中调用这些getter获取属性值,就不需要友元声明了
内容的提问来源于stack exchange,提问作者Ross Aylen
相关产品推荐
相关产品推荐

