c++ - Operator overloading: calling friend function from member function -


i have student class. want overload + operator can add double variable class. here student class:

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 done via friend function , student + double goes through member function. when compile this:

error: no matching function call ‘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 can't call friend function member function?

[update]

however when overload << operator, can call member function without pre-pending ::.

friend std::ostream &operator<<(std::ostream &os, const student &student); 

and implementation:

std::ostream &operator<<(std::ostream &os, const student &student) {     os << student.grade;     return os; } 

you're trying call member function, not friend function (cfr. c++11 7.3.1.2/3). should rather write

student student::operator+(double grade) const {     return ::operator+(grade, *this); } 

example

using :: makes sure overload resolution occurs global namespace you're in.

another way (less readable in opinion) add friend function overload resolution set

student student::operator+(double grade) const {     using ::operator+;     return operator+(grade, *this); } 

or, more readable, jarod suggested,

student student::operator+(double grade) const {     return grade + *this; } 

edit: "why": [class.friend]/p7 , [basic.lookup.argdep]/p3 explain member function same name "hides" during overload resolution name of friend function.


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -