[英]Operator overloading: calling friend function from member function
I have a Student class. 我有一个学生班。 I want to overload
+
operator so I can add a double variable to class. 我想重载
+
运算符,以便可以在类中添加一个double变量。 Here is Student
class: 这是
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;
};
And implementation: 并实现:
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
is done via friend function and Student + double
goes through member function. double + Student
通过好友功能完成, Student + double
通过成员功能完成。 When I compile I get this: 当我编译时,我得到:
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
Why I can't call a friend function from a member function? 为什么不能从成员函数调用朋友函数?
[UPDATE] [UPDATE]
However when I overload <<
operator, I can call it from member function without pre-pending ::
. 但是,当我重载
<<
运算符时,我可以从成员函数中调用它而无需预先加上::
。
friend std::ostream &operator<<(std::ostream &os, const Student &student);
and the implementation: 和实现:
std::ostream &operator<<(std::ostream &os, const Student &student) {
os << student.grade;
return os;
}
You're trying to call the member function, not the friend function (cfr. C++11 7.3.1.2/3) . 您正在尝试调用成员函数,而不是朋友函数( cfr。C ++ 11 7.3.1.2/3) 。 You should rather write
你宁愿写
Student Student::operator+(double grade) const {
return ::operator+(grade, *this);
}
Using the ::
makes sure overload resolution occurs from the global namespace you're currently in. 使用
::
可以确保从您当前所在的全局名称空间发生重载解析。
Another way (less readable in my opinion) is to add the friend function to the overload resolution set 另一种方法(我认为较不易理解)是将friend函数添加到重载解决方案集中
Student Student::operator+(double grade) const {
using ::operator+;
return operator+(grade, *this);
}
or, more readable, as Jarod suggested, 或者更具可读性,如Jarod建议的那样,
Student Student::operator+(double grade) const {
return grade + *this;
}
Edit: as for the "why": [class.friend]/p7 and [basic.lookup.argdep]/p3 explain that a member function with the same name " hides " during overload resolution the name of the friend function. 编辑:至于“为什么”: [class.friend] / p7和[basic.lookup.argdep] / p3解释说,在重载解析期间,具有相同名称“的成员函数”会隐藏 “ Friend”函数的名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.