2014-02-14 6 views
-2

В качестве задания я должен создать класс Rational для фракций и перегрузить различные операторы, чтобы манипулировать фракциями. Но у меня много проблем, чтобы разобраться, как это сделать. Вот мой код и текущие сообщения об ошибках. Любая помощь будет принята с благодарностью!Устранение неисправностей класса фракций

Редактировать: Спасибо за помощь. Он по-прежнему имеет два сообщения об ошибке. Тонна (14+) экземпляров: неопределенная ссылка на «Rational :: Rational()» 2: Когда я перегружаю оператор < <, он говорит, что num и den не определены. Как мне сказать, чтобы получить 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; 

} 
+4

И ваш вопрос ... – yizzlez

+2

Когда вы пишете код, как только вы получите одну ошибку, * stop *. Не продолжайте, пока вы не исправили эту ошибку. – Beta

+0

Вы делаете много вещей неправильно. Некоторые из них перечислены в моем ответе. – juanchopanza

ответ

1

Игнорирование каких-либо логических ошибок, я вижу несколько проблем. Там может быть больше.

Во-первых, это

RSimplify.x3; 

должен быть

x3.RSimplify(); 

Во-вторых, ваши определения арифметический оператор не соответствуют декларации другу. У вас не хватает const для РИТ:

Rational operator+(const Rational& x1, Rational& x2) { .... } 

должен быть

Rational operator+(const Rational& x1, const Rational& x2) { .... } 

В-третьих, оператор выходной поток должен воздействовать на поток вы передаете его, явно не cout. Так,

ostream &operator<<(ostream &output, const Rational &Rational) 
{ 
    return output << num << "/" << den; 
} 

Примечание также разумно оставить его вызывающему добавить endl или что-нибудь еще.

+0

Я изменил их. Огромное спасибо. – Neko

Смежные вопросы