[英]Add fractions using operator overloading
在一次采訪中,我被要求創建兩個班級。 第一個抽象類叫做Number,它支持一個操作“+”。 而另一個實現“Number”抽象類的部分。
進一步:對於一次添加的分數,它需要以原始形式顯示。 也就是說,2/4必須顯示為“2/4”,而不是“1/2”或“0.5”。
沒有提供其他細節。
以下是我的嘗試(不完整)。
我的main.cpp
#include <iostream>
#include "Fraction.h"
using namespace std;
int main()
{
Fraction sumFraction;
Fraction n11(1,2);
Fraction n21(1,2);
cout << n11.getValuenum() << "/";
cout << n11.getValueden() << endl;
cout << n21.getValuenum() << "/";
cout << n21.getValueden() << endl;
sumFraction = n11 + n21;
cout << sumFraction.getValuenum() << endl;
cout << sumFraction.getValueden() << endl;
return 0;
}
我的Numbers.h //抽象類
#pragma once
template<class T>
class Number
{
virtual T& operator= (const T &) = 0; // first parameter is implicitly passed
virtual const T operator+ (const T &) = 0;
virtual void display() = 0;
};
我的Fraction.cpp
#include "Fraction.h"
int Fraction::getValuenum()
{
return this->a1;
}
int Fraction::getValueden()
{
return this->a2;
}
Fraction::Fraction()
{
a1 = 0;
a2 = 0;
}
Fraction::Fraction(int num, int den)
{
a1 = num;
a2 = den;
}
void Fraction::display()
{
// will display the number in its original form
}
Fraction& Fraction::operator=(const Fraction &num)
{
a1 = num.a1;
a2 = num.a2;
return *this;
}
const Fraction Fraction::operator+(const Fraction &numberTwo)
{
Fraction n1;
n1.a1 = this->a1*numberTwo.a2 + this->a2*numberTwo.a1;
n1.a2 = this->a2*numberTwo.a2;
return n1;
}
我的Fraction.h
#pragma once
#include "Number.h"
class Fraction : public Number<Fraction>
{
private:
int a1;
int a2;
public:
void display();
Fraction();
Fraction(int num, int den);
int getValuenum();
int getValueden();
Fraction& operator= (const Fraction &); // first parameter is implicitly passed
const Fraction operator+ (const Fraction &); // first parameter is implicitly passed
};
以下是我的問題:
我是否真的需要為每個分數分別從我的Main函數傳遞分子和分母。 目前,我正在單獨傳遞它以跟蹤分子和分母,這可能有助於在分數方面添加和返回結果。
使用我的操作符+邏輯,如果我添加1/4 + 1/4,我得到8/16,如果我們正常添加,我猜的是2/4。 那么如何添加使用分子和分母並以這種方式保持分數,這樣如果輸出是2/4然后是2/4而不是1/2或0.5。
請幫我。
一些評論:
分數的正確(數學)加法是(*):
a/b + c/d = (ad +bc)/bd
而不是(或除了)顯示方法,我建議你寫一個ostream& operator << (ostream&, const Fraction&)
重載。 這樣你就可以只寫你的主要內容
std::cout << n11 << " + " << n21 << " = " << sumFraction << std::endl;
我沒有真正理解你的第一個問題,但我會從int添加一個轉換:
Fraction(int n): a1(n), a2(1) {};
允許直接寫入Fraction(1, 2) + 1
或Fraction(1) + Fraction(1/2)
(加法的第一個元素必須是分數)
(*)這是簡單而通用的方式。 您還可以使用最小公倍數來獲得更清晰的結果:
den = lcm(b,d)
a/b + c/d = (a * den/b) + c * den/d) / den
那樣你就得到1/4 + 2/4 = 3/4而不是12/16
但計算LCM遠不是這個答案......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.