【问题标题】:How to fix "*private variable* is a private member of '*class name*' error如何修复“*私有变量*是'*类名*'错误的私有成员
【发布时间】:2019-04-07 17:13:52
【问题描述】:

我正在编写使用友元函数的代码,但我不确定为什么我在函数“sum”中收到错误“is a private member of”,因为我在头文件中将该函数声明为友元。

头文件:

#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 (const rational&amp; r1, const rational&amp; r2);rational sum (rational r1, rational r2) 是两个不同的函数,它们的参数声明不匹配
  • 如果你有像getNumeratorgetDenominator这样的“getter”函数,为什么你需要让sum函数成为朋友呢?友元函数通常会使事情复杂化,倾向于使代码更混乱且不易维护。当然也有例外(输入和输出运算符重载通常是其中之一),但通常尽量避免它们。
  • 我认为你的声明需要说rational rational::sum (rational r1, rational r2)

标签: c++ friend-function


【解决方案1】:

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

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

总体评论:使用大写的首字母类 (Rational)

【讨论】:

  • 声明的目的是使用朋友声明,所以全局函数应该是rational sum (const rational&amp; r1, const rational&amp; r2)
  • 当我将其更改为您建议的实现时,出现错误“使用未声明的标识符'分子''。(有理总和(常量理性& r1,常量理性& r2))
  • @user10793479 当然,请注意我的答案中额外的ints
【解决方案2】:

你想要这样的东西:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-07
    • 1970-01-01
    • 2015-11-15
    • 2015-05-04
    • 2015-05-17
    相关资源
    最近更新 更多