Created
June 14, 2019 15:14
-
-
Save tabvn/61d2771fea5cf745d16e6a3fa92ac198 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
template <class T> | |
class Fraction { | |
private: | |
T tu,mau; | |
public: | |
void setTu(T a){ | |
Fraction::tu = a; | |
} | |
virtual void setMau(T a){ | |
Fraction::mau = a; | |
} | |
T getTu(){ | |
return Fraction::tu; | |
} | |
T getMau(){ | |
return Fraction::mau; | |
} | |
Fraction<T> operator + (Fraction x){ | |
Fraction<T> c; | |
T kqTu = (Fraction::tu * x.getMau()) + (x.getTu() * Fraction::mau); | |
T kqMau = (Fraction::mau * x.getMau()); | |
c.setTu(kqTu); | |
c.setMau(kqMau); | |
return c; | |
} | |
}; | |
template <class T> | |
class CheckedFraction : public Fraction<T>{ | |
public: | |
void setMau(T x) override { | |
if (x != 0){ | |
Fraction<T>::setMau(x); | |
} | |
} | |
CheckedFraction<T> add(Fraction<T> f1, Fraction<T> f2){ | |
// 1/2 + 1/2 | |
Fraction<T> f3 = f1 + f2; | |
CheckedFraction c; | |
c.setTu(f3.getTu()); | |
c.setMau(f3.getMau()); | |
return c; | |
} | |
}; | |
int main() { | |
Fraction<int> f1, f2; | |
f1.setTu(1); | |
f1.setMau(2); | |
f2.setTu(1); | |
f2.setMau(2); | |
CheckedFraction<int> c; | |
c = c.add(f1,f2); | |
cout << "Ket qua cua phep tong 2 phan so la:" << c.getTu() << "/" << c.getMau(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment