作爲一項任務,我應該爲分數創建一個Rational類,並重載各種操作符以操縱分數。但我在清理如何做這件事方面遇到了很多麻煩。這是我的代碼和當前的錯誤消息。任何幫助將不勝感激!分數類故障排除
編輯:感謝您的幫助。它仍然有兩個錯誤消息。 一噸(14+)的實例:未定義的引用'Rational :: Rational()' 2:當我超載< <運算符它說num和den沒有定義。我如何告訴它從它應該打印出來的對象中獲取數字和書房? 謝謝!
頭文件
#ifndef Rational_H
#define Rational_H
#include<iostream>
#include <string>
using namespace std;
class Rational
{
friend Rational operator+(const Rational& x1, const Rational& x2);
friend Rational operator-(const Rational& x1, const Rational& x2);
friend Rational operator*(const Rational& x1, const Rational& x2);
public:
Rational(); //constructor
void setFraction(int, int); //set fractional
int getNum() const;
int getDen() const;
void RSimplify();
void printFraction();
friend ostream &operator<<(ostream &, const Rational &);
friend istream &operator>>(istream &, Rational &);
private:
int num;
int den;
};
#endif
.cpp文件
#include <iomanip>
#include "Rational.h"
using namespace std;
int Rational::getNum() const
{
return num;
}
int Rational::getDen() const
{
return den;
}
ostream &operator<<(ostream &output, const ATJRational &ATJRational)
{
return output << num << "/" << den;
Error: num and den are not declared in this scope
}
istream &operator>>(istream &input, ATJRational &ATJRational)
{
char slash;
return input >> ATJRational.num >> slash >> ATJRational.den;
ATJRational.RSimplify();
}
void ATJRational::RSimplify()
{
for(int i=2; i<14; i++)
{
while(den % i == 0)
{
if(num % i == 0)
{
den = den/i;
num = num/i;
}
}
}
}
Rational operator+(const Rational& x1, const Rational& x2)
{
Rational x3;
x3.num = (x1.num * x2.den) + (x2.num * x1.den);
x3.den = (x1.den * x2.den);
x3.RSimplify();
return x3;
}
Rational operator-(const Rational& x1, const Rational& x2)
{
Rational x3; // result
x3.num = (x1.num * x2.den) - (x2.num * x1.den);
x3.den = (x1.den * x2.den);
x3.RSimplify();
return x3;
}
Rational operator*(const Rational& x1, const Rational& x2)
{
Rational x3; // result
x3.num = (x1.num * x2.num);
x3.den = (x1.den * x2.den);
x3.RSimplify();
return x3;
}
主文件
#include <iostream>
#include "Rational.h"
using namespace std;
int main()
{
Rational x1; //create object fraction
Rational x2;
Rational x3;
cout<<"Enter a fraction in the form 1/4:"<<endl;
cin>>x1;
cout<<"Enter a 2nd fraction in the form 1/4:"<<endl;
cin>>x2;
cout<<"The two fractions in their lowest terms are: "<<x1<<" and "<<x2<<endl;
cout<<"Adding the 1st and 2nd fractions together..."<<endl;
x3 = x1 + x2;
cout<<"The sum of the two fractions is:"<<x3<<endl;
cout<<"Subtracting the 1st fraction from the 2nd fraction..."<<endl;
x3 = x2 - x1;
cout<<"The result is:"<<x3<<endl;
cout<<"Multiplying the 1st fraction by the 2nd fraction..."<<endl;
x3 = x1 * x2;
cout<<"The product is:"<<x3<<endl;
}
而你的問題是...... – yizzlez
當你寫代碼時,只要你遇到一個錯誤,* stop *。不要繼續,直到你修復了這個錯誤。 – Beta
你做錯了很多事情。其中一些列在我的答案中。 – juanchopanza