我有一个学生班。我想重载+
运算符,所以我可以在类中添加一个double变量。这是Student
类:
class Student {
private:
std::string firstName;
double grade;
public:
Student(const std::string &firstName, double grade);
double getGrade() const;
friend Student operator+(double grade, const Student &student);
Student operator+(double grade) const;
};
并实施:
Student::Student(const std::string &firstName, double grade) {
this->firstName = firstName;
this->grade = grade;
}
double Student::getGrade() const {
return grade;
}
Student operator+(double grade, const Student &student) {
return Student(student.firstName, student.grade + grade);
}
Student Student::operator+(double grade) const {
return operator+(grade, *this);
}
double + Student
通过友元函数完成,Student + double
通过成员函数完成。当我编译时,我得到了这个:
error: no matching function for call to ‘Student::operator+(double&, const Student&) const’
return operator+(grade, *this);
^
note: candidate is:
note: Student Student::operator+(double) const
Student Student::operator+(double grade) const {
^
note: candidate expects 1 argument, 2 provided
为什么我不能从成员函数中调用朋友函数?
[UPDATE]
但是当我重载<<
运算符时,我可以在没有预先挂起::
的情况下从成员函数调用它。
friend std::ostream &operator<<(std::ostream &os, const Student &student);
和实施:
std::ostream &operator<<(std::ostream &os, const Student &student) {
os << student.grade;
return os;
}
答案 0 :(得分:3)
您正在尝试调用成员函数,而不是友元函数(cfr.C ++ 11 7.3.1.2/3)。你应该写
Student Student::operator+(double grade) const {
return ::operator+(grade, *this);
}
使用::
可确保从您当前所在的全局命名空间中发生重载解析。
另一种方式(在我看来可读性较差)是将友元函数添加到重载决策集
Student Student::operator+(double grade) const {
using ::operator+;
return operator+(grade, *this);
}
或者,如Jarod所说,更具可读性,
Student Student::operator+(double grade) const {
return grade + *this;
}
编辑:至于“为什么”: [class.friend] / p7 和 [basic.lookup.argdep] / p3 解释一个成员函数与在重载解析期间,同名“hides”是友元函数的名称。