如何使用c ++中的类编写Rational Fractions

时间:2018-05-15 04:41:17

标签: c++ copy-constructor static-members fractions rational-number

我必须实现Rational类才能获得Rational分数。 header.h文件由我的导师提供,因此我必须跟进。我还必须在Rational::Rational(const Rational& cRational)函数中编写复制构造函数,以便可以复制object。我编写了我的代码,但在输出中添加分数是错误的。任何人都可以帮我解决这个问题吗?我的编码在Rational::addition(const Rational &a)中有什么问题或者我该如何解决?

输出:

 Begin Rational Class Tests

Testing default constructor: 1/1

Testing std constructor: 1/2

Testing copy constructor: 1/2

Testing addition: 4/4 + 1/2 = 4/4    // it should be 1/2 + 1/2 = 4/4

主要功能:

int main()
{
    cout << "Begin Rational Class Tests\n\n";

    cout<<"Testing default constructor: ";
    Rational n1;
    n1.printRational();
    cout << endl << endl;

    cout<<"Testing std constructor: ";
    Rational n2(1,2);
    n2.printRational();
    cout << endl << endl;

    cout<<"Testing copy constructor: ";
    Rational n3(n2);
    n3.printRational();
    cout << endl << endl;

    cout<<"Testing addition: ";
    n1 = n2.addition(n3);
    n2.printRational();
    cout <<" + ";
    n3.printRational();
    cout <<" = ";
    n1.printRational();
    cout << endl << endl;
}

标题文件:

class Rational {
  public:
    Rational();  // default constructor
    Rational(int, int); //std (initialisation) constructor
    Rational(const Rational&); //copy constructor
    Rational addition(const Rational &);
    void printRational();
  private:
    int numerator;
    int denominator;
};

我的节目:

//default constructor
Rational::Rational() 
{
   numerator = 1;
   denominator = 1;
}
//initialize constructor
Rational::Rational(int n, int d)
{
     numerator = n;
     if (d==0) 
     {
        cout << "ERROR: ATTEMPTING TO DIVIDE BY ZERO" << endl;
        exit(0); // will terminate the program if division by 0 is attempted
     }
     else
        denominator = d;
}
//copy constructor
Rational::Rational(const Rational& cRational)
{
    numerator = cRational.numerator;
    denominator = cRational.denominator;
}
//addition
Rational Rational::addition(const Rational &a)
{
     numerator = numerator * a.denominator + a.numerator * denominator;
     denominator = denominator * a.denominator;
     return Rational(numerator,denominator);
}

void Rational::printRational()
{
    cout << numerator << "/" << denominator ;
}

2 个答案:

答案 0 :(得分:1)

除了()之外,只需为分子和分母的新值创建具有不同名称的新变量,就像这样......

int n, d;  //you could use better names
n = numerator * a.denominator + a.numerator * denominator;
d = denominator * a.denominator;
return Rational(n, d);

我查了一下,这有效here

一般情况下,不要在同一范围内对两个变量使用相同的名称。

答案 1 :(得分:1)

你的添加功能正在修改*this的成员变量,这会导致奇怪的事情发生

是一个更合适的原型
Rational addition(const Rational &) const;

因为这会让编译器告诉你,你正在做一些奇怪的事情。

您可以使用局部变量而不是分配给成员,也可以完全不使用中间变量:

Rational Rational::addition(const Rational &a)
{
     return Rational(numerator * a.denominator + a.numerator * denominator, 
                     denominator * a.denominator);
}