Cách sử dụng copy constructor trong C++
#include <iostream>
#include<math.h>
using namespace std;
class Fraction
{
private:
int tu;
int mau;
public:
// 2. Default constructor
Fraction()
{
tu = 0;
mau = 1;
}
// 3. Parameterized constructor
Fraction(int num, int den) {
tu = num;
mau = (den == 0) ? 1 : den; // Tránh chia cho 0
}
// 4. Copy constructor
Fraction(const Fraction &other)
{
tu = other.tu;
mau = other.mau;
}
// 5. Overload input operator >>
friend istream& operator>>(istream& is, Fraction& f) {
cout << "Enter tu: ";
is >> f.tu;
cout << "Enter mau (? 0): ";
is >> f.mau;
if (f.mau == 0) {
cout << "Invalid mau. Reset to 1.\n";
f.mau = 1;
}
reduceFraction(f);
return is;
}
// 6. Overload output operator <<
friend ostream& operator<<(ostream& os, const Fraction& f) {
os << f.tu << "/" << f.mau;
return os;
}
// 7. Overload + operator
Fraction operator+(const Fraction& other) {
Fraction result;
result.tu = tu * other.mau + other.tu * mau;
result.mau = mau * other.mau;
reduceFraction(result);
return result;
}
// 8. Overload / operator
Fraction operator/(const Fraction& other) {
Fraction result;
result.tu = tu * other.mau;
result.mau = mau * other.tu;
if (result.mau == 0) {
cout << "Division by zero. Reset result to 0/1.\n";
result.tu = 0;
result.mau = 1;
}
reduceFraction(result);
return result;
}
// 9. Overload == operator (returns -1, 0, 1)
int operator==(const Fraction& other) const
{
int lhs = tu * other.mau;
int rhs = other.tu * mau;
if (lhs < rhs) return -1;
else if (lhs > rhs) return 1;
else return 0;
}
// 10. Friend function to reduce fraction
friend void reduceFraction(Fraction &f);
};
// Helper: Tìm U?c chung l?n nh?t (GCD)
int gcd(int a, int b) {
while (b != 0) {
int r = a % b;
a = b;
b = r;
}
return a;
}
// 10. Friend function to reduce a fraction
void reduceFraction(Fraction &f)
{
if (f.tu == 0)
{
f.mau = 1;
return;
}
int g = gcd(abs(f.tu), abs(f.mau));
f.tu /= g;
f.mau /= g;
// Ðua d?u âm v? t? s?
if (f.mau < 0) {
f.tu *= -1;
f.tu *= -1;
}
}
int main() {
Fraction f1, f2;
// Nh?p hai phân s?
cout << "Enter first fraction:\n";
cin >> f1;
cout << "Enter second fraction:\n";
cin >> f2;
// In ra hai phân s?
cout << "\nFraction 1: " << f1 << endl;
cout << "Fraction 2: " << f2 << endl;
// C?ng hai phân s?
Fraction sum = f1 + f2;
cout << "\nSum: " << sum << endl;
// Chia hai phân s?
Fraction result = f1 / f2;
cout << "Division result: " << result << endl;
// So sánh hai phân s?
int comparison = f1 == f2;
if (comparison == 0) {
cout << "The two fractions are equal.\n";
} else if (comparison < 0) {
cout << "Fraction 1 is smaller than Fraction 2.\n";
} else {
cout << "Fraction 1 is greater than Fraction 2.\n";
}
return 0;
}
Trương Đình Huy

