如何修复“ * private变量*是'* class name *”的私有成员错误

时间:2019-04-07 17:13:53

标签: c++ friend-function

我正在编写使用好友函数的代码,但是由于我在头文件中将该函数声明为好友,所以我不确定为什么在函数“ sum”中出现错误“是”的私有成员的消息。

头文件:

#include <iostream>

class rational
{
public:

    // ToDo: Constructor that takes int numerator and int denominator
    rational (int numerator = 0, int denominator = 1);
   // ToDo: Member function to write a rational as n/d
    void set (int set_numerator, int set_denominator);
    // ToDo: declare an accessor function to get the numerator
    int  getNumerator () const;
    // ToDo: declare an accessor function to get the denominator
    int  getDenominator () const;
    // ToDo: declare a function called Sum that takes two rational objects
    // sets the current object to the sum of the given objects using the
    // formula: a/b + c/d = ( a*d + b*c)/(b*d)
    friend rational sum (const rational& r1, const rational& r2);

    void output (std::ostream& out);
    // member function to display the object

    void input (std::istream& in);


private:

    int numerator;
    int denominator;

};

源文件:

#include <iostream>
using namespace std;


//  takes two rational objects and uses the formula a/b + c/d = ( a*d + b*c)/(b*d) to change the numerator and denominator


rational sum (rational r1, rational r2)
{
    // formula: a/b + c/d = ( a*d + b*c)/(b*d)

    cout << endl;

    numerator = ((r2.denominator * r1.numerator) + (r1.denominator * r2.numerator));

    denominator = (r1.denominator * r2.denominator);
}

2 个答案:

答案 0 :(得分:1)

rational sum (rational r1, rational r2)是一个全新的函数(无法与类rational相关),它接受两个有理数并返回有理数。

实现所需的类方法的正确方法是rational rational::sum (const rational& r1, const rational& r2)

总体注释:对课程(Rational)使用大写的首字母

答案 1 :(得分:0)

您想要这样的东西:

rational sum (const rational& r1, const rational& r2)
{
    // formula: a/b + c/d = ( a*d + b*c)/(b*d)

    int numerator = ((r2.denominator * r1.numerator) + (r1.denominator * r2.numerator));

    int denominator = (r1.denominator * r2.denominator);
    return rational(numerator, denominator);
}