Как исправить "* приватная переменная * является приватным членом ошибки '* class name *' - PullRequest
0 голосов
/ 07 апреля 2019

Я пишу код, который использует функции друзей, но я не уверен, почему я получаю сообщение об ошибке "является частным членом" в функции "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 ]

1 голос
/ 07 апреля 2019

rational sum (rational r1, rational r2) - это совершенно новая функция (никак не связанная с классом rational), которая принимает два рациональных значения и возвращает рациональное значение.

Правильный способ реализации необходимого метода класса:1005 *

Общий комментарий: используйте заглавную первую букву для классов (Rational)

0 голосов
/ 07 апреля 2019

Вы хотите что-то вроде этого:

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);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...