我想重载“=”运算符,但它给了我错误

时间:2021-04-01 18:54:02
friend Fraction operator=(const Fraction &newfraction) {

    Fraction changedfraction;

    changedfraction.numerator = newfraction.numerator;
    changedfraction.denominator = newfraction.denominator;

    changedfraction.simplify(changedfraction.numerator, 
                             changedfraction.denominator);
    return (changedfraction);
}

1 个解决方案

#1


An assignment operator with signature Fraction operator=(const Fraction &newfraction) has to be a member function. A friend function is not a member. So the numbers of parameters don't match the 2 needed for assignment. Remove the friend and make sure it is declared as a member function.

具有签名Fraction operator =(const Fraction&newfraction)的赋值运算符必须是成员函数。朋友功能不是会员。因此,参数的数量与分配所需的2不匹配。删除好友并确保将其声明为成员函数。

struct Fraction
{
  Fraction& operator=(const Fraction &newfraction) { .... }
  ....
};

Also note that traditionally the assignment operator returns a reference to *this, not a value.

另请注意,传统上赋值运算符返回对* this的引用,而不是值。

#1


An assignment operator with signature Fraction operator=(const Fraction &newfraction) has to be a member function. A friend function is not a member. So the numbers of parameters don't match the 2 needed for assignment. Remove the friend and make sure it is declared as a member function.

具有签名Fraction operator =(const Fraction&newfraction)的赋值运算符必须是成员函数。朋友功能不是会员。因此,参数的数量与分配所需的2不匹配。删除好友并确保将其声明为成员函数。

struct Fraction
{
  Fraction& operator=(const Fraction &newfraction) { .... }
  ....
};

Also note that traditionally the assignment operator returns a reference to *this, not a value.

另请注意,传统上赋值运算符返回对* this的引用,而不是值。