首页 > 解决方案 > 使用类中的值设置等于新值而不更改先前值c ++

问题描述

我正在使用有理数的类结构。我试图基本上将 r2 值用于 num 和 den (分子和分母),并让它们为负并等于 r3。而 r3.output(cout, "r3") 应该输出
r3: 4/1。

代码的当前输出(当我移除 r3 时):
r1: 10/3
r2 = -4/1

我无法掌握如何从本质上返回类数据以将 r3 的值设置为等于负 r2 的值。我必须使用 int 主要命令,因此无法更改。

谢谢,这是我第一次真正的课,所以会很乱。请忽略其他操作数,我还没有讲到这些。

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

class rational {
    int num,den,nummod,denmod;
public:
    rational (int,int); //Constructor
    int gcd (int n1 ,int n2); //Finds GCD
    int simplified(int x, int y,int z); //Simplifies the fraction
    //IO
    int input();
    void output(ostream& y, string label); //Outputs the fraction

    //Expressions
    int neg(void);

    rational &sub();
    rational &add();
    rational &mul();
    rational &div();

};

rational::rational(int x,int y)
{
    if(y == 0) //make it throw a cerr error and exit with -1.
    {
        cout<<"0 in denominator error"<<'\n';
        return;
    }
    int z = gcd(x,y);
    simplified(x,y,z); //Gets the simplified numerator and denominator
    return;
}
int rational::simplified(int x, int y, int z) {
    num = x/z;
    den = y/z;
    return 1;
}

int rational::gcd(int n1, int n2) { //Code provided by the homework
    int tmp;
    while (n2 != 0) {
        tmp = n1;
        n1 = n2;
        n2 = tmp % n2;
    }
}

void rational::output(ostream &y, string label) {
    if(cout)
    {
        string fraction = to_string(num) + "/" + to_string(den);
        cout<<label<<": "<<fraction<<'\n';
        return;
    }
    //if()
    //{
    //    return;
    //}
}

int rational::neg(void) {r2.neg();
    int temp;
    if (num < 0) {
        num =num * -1;
    }
    if (den < 0) {
        den =den * -1;
    }
    return 0;
}


int main(void)
{
    rational r1(10, 3);
    rational r2(8, -2);

    r1.output(cout, "r1");
    r2.output(cout, "r2");
    rational r3 = r2.neg();  //This is the error
    r3.output(cout, "r3");

    return 0;
}

标签: c++

解决方案


你永远不会初始化 r3。它可能应该发出警告(可能带有 -Wextra g++ 标志或类似的东西)。正如 Botje 所提到的,一种选择是将 neg() 编码为 Rational 对象的构造函数,该对象接受对被否定的 Rational 对象的引用。

另一种选择是将 neg() 编码为 void 函数,它简单地否定调用它的列表(例如r2.neg()否定 r2)。这仍然需要一种使 r3 成为 r2 的副本的方法。

最后,this->in you neg() 函数是不必要的,因为范围解析运算符rational::会将您置于需要访问该(成员函数)的范围内


推荐阅读