2014-09-10 3 views
-2

누군가이 코드의 내용을 설명 할 수 있습니까? 당신은 줄을 서서 갈 필요는 없지만 일반적인 요약은 정말 도움이 될 것입니다. 다른 소수 클래스 C++ 코드와 비슷하기 때문에이 코드를 완전히 참조 할 필요가 없습니다.C++ 설명의 분수 클래스

#include<iostream> 

using namespace std; 

class Fraction 

{ 

    private: 

    int num, den; 

    public: 

    Fraction(int n = 1, int d = 2) : num(n), den(d) { } 

    void show() { cout«num«”/”«den; } 

    Fraction operator+(Fraction f) const 

    { return Fraction(num+f.num, den+f.den); } 

    Fraction operator-(Fraction f) const 

    { return Fraction(num-f.num, den-f.den); } 

    Fraction operator*(Fraction f) const 

    { return Fraction(num*f.num, den*f.den); } 

    Fraction operator/(Fraction f) const 

    { 

    int rNum = (f.den*num)/den; 

    return (rNum, f.num); 

    } 

    friend ostream& operator«(ostream& out, Fraction& f) 

    { cout«f.num«”/”«f.den; return out; } 

    friend istream& operator»(istream& in, Fraction& f) 

    { cout«”\nEnter Numerator: “; cin»f.num; cout«”Enter Denominator: “; 

    cin»f.den; cout«f.num«”/”«f.den; return in; } 

    int ndMax() 

    { return (num<=den) ? num:den; } 

    void reduce() 

    { 

    for(int i = 2; i<=ndMax(); i++) 

    if(num%i == 0 && den%i == 0) 

    { num = num/i; den = den/i; i = 1; } 

    } 

}; // 

int main() 

{ 

    Fraction f1(5, 6); 

    Fraction f2(80, 1001); 

    cout«f1«” and “«f2«endl; 

    Fraction f3 = f1/f2; 

    f3.reduce(); cout«f3; 

    cout«endl; 

    return 0; 

} 
+1

클래스는 약간의 오버로드 된 연산자를 지원하고 수학은 어떤 부분이 추가 설명이 필요합니다 .. (이 수학 과정에서 종이에 할 것 같은) 별도의 분자와 분모에 따라 않는 정의? – user2864740

+0

이 수업은 나쁘게 디자인 된 것처럼 보입니다. operator +()와 operator-()의 구현은 분수의 정상적인 덧셈과 뺄셈을 수행하는 것이 아니라 분자와 분모의 덧셈/뺄셈의 무의미한 연산을 수행합니다. – mattnewport

+0

예 매트. 나는 방금 그것의 논리를 바꿨고 지금은 잘 작동하고있는 것 같습니다. 아직도 나를 혼란스럽게하는 주요 부분은이 줄입니다. 분수 (int n = 1, int d = 2) : num (n), den (d) {}. 여기서 무슨 일이 일어나고있는거야? 또한, 개인 변수의 요점은 무엇입니까? – pr0grammingIsFun

답변

1
// This declares a dependency on the system module, iostream. Specifically, this code uses the 
// system provided objects, cout, and cin, for output and input. 
#include <iostream> 

// This says if the compiler cannot find a symbol, it should try looking in the namespace, std. 
using namespace std; 

// This defines a type called, Fraction. 
class Fraction { 
private: 
    // This declares two private member variables, num, and den, presumably representing the 
    // numerator and denominator of a fraction. Each object of type Fraction will have its own 
    // num and den. Because they are private they cannot be accidentally modified outside the 
    // definition of Fraction. They are the module's secret. 
    int num, den; 

public: 
    // This declares a constructor. It uses the default argument notation to actually define 
    // three constructor syntaxes. Two arguments may be given, one, or zero. Fraction() = 1/2, 
    // Fraction(x) = x/2, and Fraction(x, y) = x/y. A default denominator of 1 would be more 
    // normal, especially since this constructor can be used to implicitly convert an int into 
    // a Fraction. 
    Fraction(int n = 1, int d = 2) : num(n), den(d) { } 

    // This function outputs a representation of a Fraction to cout. It repeats the definition 
    // of operator<< below, which violates the DRY principle so it should probably be written 
    // as: cout << *this; 
    void show() { 
    cout << num << "/" << den; } 

    // This is an operator overload. It allows you to write, Fraction + Fraction. Note that it 
    // does not add fractions in the expected way, instead it does a vector addition. 
    Fraction operator+(Fraction f) const { 
    return Fraction(num + f.num, den + f.den); } 

    // Similarly broken. 
    Fraction operator-(Fraction f) const { 
    return Fraction(num - f.num, den - f.den); } 

    // Correct multiplication, although normalizing the fraction is kind of expected. 
    Fraction operator*(Fraction f) const { 
    return Fraction(num * f.num, den * f.den); } 

    // Cannot be bothered to decide if this is correct. Multiplying by the inverse would be the 
    // more obvious thing to do, like: return *this * Fraction(f.den, f.num); 
    Fraction operator/(Fraction f) const { 
    int rNum = (f.den * num)/den; 
    return Fraction(rNum, f.num); } 

    // These functions support reading and writing a Fraction using streams. Note that they should 
    // make use of the out and in parameters, then they would work with all stream types. 
    friend ostream& operator<<(ostream& out, Fraction& f) { 
    cout << f.num << "/" << f.den; 
    return out; } 
    // The prompts here are poor design. 
    friend istream& operator>>(istream& in, Fraction& f) { 
    cout << "\nEnter Numerator: "; 
    cin >> f.num; 
    cout << "Enter Denominator: "; 
    cin >> f.den; 
    cout << f.num << "/" << f.den; 
    return in; } 

    // This function does not do what you would expect based on the name. It returns min(num, den). 
    // It should be declared const, like operator+ is since it is thread-safe. 
    int ndMax() { 
    return (num <= den) ? num : den; } 

    // This is weird and evil. The intent is to normalize the fraction. Euclid's algorithm would 
    // be the usual way. 
    void reduce() { 
    for (int i = 2; i <= ndMax(); i++) 
     if (num % i == 0 && den % i == 0) { 
     num = num/i; 
     den = den/i; 
     i = 1; // Evil!!! Do not modify the loop variable in the body of the loop. 
     } } 

    // There are a number of other functions, not explicit here, that are implicitly generated 
    // by the compiler. For example a copy constructor and assignment operator. 
}; 

// This is a simple test driver for the Fraction class. 
int main() { 
    Fraction f1(5, 6); 
    Fraction f2(80, 1001); 
    cout << f1 << " and " << f2 << endl; 
    Fraction f3 = f1/f2; 
    f3.reduce(); 
    cout << f3; 
    cout << endl; 
    return 0; } 
+0

정말 고마워요! 내가 기대했던 것보다 훨씬 더 많은 정보. 나는 여전히 대중 앞에서 혼란 스럽다. 내 C + + 구문 지식은 매우 나쁘다. 왜 거기에 ":"가 있으며 왜 ";" 결국. 또한 이와 같은 생성자를 선언해야합니까? 또한 선생님은 다른 프로그램에서 인수가없는 생성자를 선언했으며 다른 행에서 수행했습니다. MyString(); MyString (문자열 a); 그게 여기에서 할 수 있을까요? – pr0grammingIsFun

+0

함수 정의는 세미콜론으로 끝나지 않습니다. 이 생성자뿐만 아니라 함수 정의는 세미콜론으로 끝나지 않습니다. 콜론은 생성자 초기화 목록의 시작을 표시합니다. 예, 기본 매개 변수 대신 세 개의 별도 생성자를 선언 할 수 있습니다. –