c++ - 如何修复 "*private variable* is a private member of ' *类名*' 错误

标签 c++ friend-function

我正在编写使用友元函数的代码,但我不确定为什么在函数“sum”中出现错误“是一个私有(private)成员”,因为我在头文件中将该函数声明为友元。

头文件:

#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);
}

最佳答案

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

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

总体评价:对类使用首字母大写(Rational)

关于c++ - 如何修复 "*private variable* is a private member of ' *类名*' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55561675/

相关文章:

c++ - 我刚刚了解了 C++ 中的动态内存分配

c++ - 与默认构造函数 : clang produces parse error while gcc did not 成为 friend

c++ - 接受类参数的友元函数的尾随返回类型

c++ - 运算符重载 : member function vs. 非成员函数?

c++ - 为什么 test2 + test3 的运算符 << 不能重载?

c++ - 右移无法正常工作

c++ - 使用模板调用重载函数(unresolved overloaded function type compiler error)

c++ - 找不到 C++ 代码中的错误

c++ - 使用 boost::bind 的调用错误没有匹配函数

c++ - 如何解决 "class must be used when declaring a friend"错误?