【问题标题】:Operator overloading: calling friend function from member function运算符重载:从成员函数调用友元函数
【发布时间】:2015-05-15 07:10:14
【问题描述】:

我有一个学生班。我想重载+ 运算符,这样我就可以在类中添加一个双变量。这是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

为什么我不能从成员函数调用友元函数?

[更新]

但是,当我重载 << 运算符时,我可以从成员函数中调用它,而无需预先挂起 ::

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

和实施:

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

【问题讨论】:

    标签: c++ operator-overloading friend-function


    【解决方案1】:

    您正在尝试调用成员函数,而不是友元函数 (cfr. C++11 7.3.1.2/3)。你应该写

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

    Example

    使用:: 可确保从您当前所在的全局命名空间发生重载解析。

    另一种方式(我认为可读性较差)是将友元函数添加到重载解析集

    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”友元函数的名称。

    【讨论】:

    • 或者干脆grade + *this
    • 您的解决方案解决了问题,但提出了另一个问题。查看更新。
    • @MajidAzimi 编辑了帖子。请继续阅读。
    猜你喜欢
    • 1970-01-01
    • 2010-12-26
    • 2017-07-26
    • 1970-01-01
    • 2021-05-10
    • 1970-01-01
    • 2011-06-05
    • 1970-01-01
    相关资源
    最近更新 更多