cpp

exercises

exercises.cpp⚙️
/**
 * Operator Overloading - Exercises
 * Compile: g++ -std=c++17 -Wall exercises.cpp -o exercises
 */

#include <iostream>
#include <string>
#include <cmath>
using namespace std;

// ============================================================
// Exercise 1: Arithmetic Operators ⭐
// ============================================================

class Fraction {
    int num, den;
public:
    Fraction(int n = 0, int d = 1) : num(n), den(d) {}
    
    // TODO: Implement operator+ and operator*
    // Fraction + Fraction: (a/b + c/d) = (ad + bc) / bd
    // Fraction * Fraction: (a/b * c/d) = ac / bd
    
    friend ostream& operator<<(ostream& os, const Fraction& f) {
        return os << f.num << "/" << f.den;
    }
};

void exercise1() {
    Fraction a(1, 2), b(1, 3);
    cout << a << " + " << b << " = ?" << endl;  // Should be 5/6
    cout << a << " * " << b << " = ?" << endl;  // Should be 1/6
}

// ============================================================
// Exercise 2: Comparison Operators ⭐⭐
// ============================================================

class Money {
    int cents;  // Store everything in cents
public:
    Money(int dollars = 0, int c = 0) : cents(dollars * 100 + c) {}
    
    // TODO: Implement ==, !=, <, >, <=, >=
    
    friend ostream& operator<<(ostream& os, const Money& m) {
        return os << "$" << m.cents / 100 << "." << (m.cents % 100 < 10 ? "0" : "") << m.cents % 100;
    }
};

void exercise2() {
    Money m1(10, 50), m2(10, 50), m3(20, 0);
    cout << m1 << " == " << m2 << ": ?" << endl;  // true
    cout << m1 << " < " << m3 << ": ?" << endl;   // true
}

// ============================================================
// Exercise 3: Stream Operators ⭐⭐
// ============================================================

class Rectangle {
    double width, height;
public:
    Rectangle(double w = 0, double h = 0) : width(w), height(h) {}
    
    // TODO: Implement operator<< to print "Rectangle(w x h)"
    // TODO: Implement operator>> to read width and height
};

void exercise3() {
    Rectangle r(5, 3);
    // cout << r << endl;  // Rectangle(5 x 3)
    cout << "(Implement stream operators)" << endl;
}

// ============================================================
// Exercise 4: Subscript Operator ⭐⭐
// ============================================================

class SafeArray {
    int* data;
    size_t size;
public:
    SafeArray(size_t n) : data(new int[n]()), size(n) {}
    ~SafeArray() { delete[] data; }
    
    // TODO: Implement operator[] with bounds checking
    // Throw out_of_range if index >= size
    
    size_t getSize() const { return size; }
};

void exercise4() {
    SafeArray arr(5);
    // arr[0] = 10;
    // arr[10] = 20;  // Should throw
    cout << "(Implement SafeArray[])" << endl;
}

// ============================================================
// Exercise 5: Function Call Operator ⭐⭐
// ============================================================

// TODO: Create a functor "Power" that raises x to power n
class Power {
    int exponent;
public:
    Power(int n) : exponent(n) {}
    // int operator()(int x) const { ... }
};

void exercise5() {
    // Power square(2), cube(3);
    // cout << "5^2 = " << square(5) << endl;  // 25
    // cout << "3^3 = " << cube(3) << endl;    // 27
    cout << "(Implement Power functor)" << endl;
}

// ============================================================
// Exercise 6: Increment/Decrement ⭐⭐
// ============================================================

class Time {
    int hours, minutes;
    void normalize() {
        hours += minutes / 60;
        minutes %= 60;
        hours %= 24;
    }
public:
    Time(int h = 0, int m = 0) : hours(h), minutes(m) { normalize(); }
    
    // TODO: Implement pre/post ++ to add 1 minute
    // TODO: Implement pre/post -- to subtract 1 minute
    
    friend ostream& operator<<(ostream& os, const Time& t) {
        return os << (t.hours < 10 ? "0" : "") << t.hours << ":" 
                  << (t.minutes < 10 ? "0" : "") << t.minutes;
    }
};

void exercise6() {
    Time t(10, 30);
    cout << "Time: " << t << endl;
    // cout << "++t: " << ++t << endl;  // 10:31
    // cout << "t++: " << t++ << endl;  // 10:31, then becomes 10:32
    cout << "(Implement ++/--)" << endl;
}

// ============================================================
// Exercise 7: Complete Class ⭐⭐⭐
// ============================================================

class Vector3D {
    double x, y, z;
public:
    Vector3D(double x = 0, double y = 0, double z = 0) : x(x), y(y), z(z) {}
    
    // TODO: Implement:
    // - operator+ (add vectors)
    // - operator- (subtract vectors)
    // - operator* (dot product: a*b = ax*bx + ay*by + az*bz)
    // - operator* (scalar: Vector * double)
    // - operator-() (negate)
    // - operator== and operator!=
    // - operator<< (stream)
    
    double magnitude() const { return sqrt(x*x + y*y + z*z); }
};

void exercise7() {
    Vector3D a(1, 2, 3), b(4, 5, 6);
    // cout << "a + b = " << (a + b) << endl;
    // cout << "a * b (dot) = " << (a * b) << endl;
    // cout << "a * 2 = " << (a * 2.0) << endl;
    cout << "(Implement Vector3D operators)" << endl;
}

// ============================================================
// Exercise 8: Matrix Class ⭐⭐⭐
// ============================================================

class Matrix2x2 {
    double data[2][2];
public:
    Matrix2x2(double a = 0, double b = 0, double c = 0, double d = 0) {
        data[0][0] = a; data[0][1] = b;
        data[1][0] = c; data[1][1] = d;
    }
    
    // TODO: Implement:
    // - operator+ (add matrices)
    // - operator* (matrix multiplication)
    // - operator()(int i, int j) to access elements
    // - operator<< (stream)
};

void exercise8() {
    Matrix2x2 A(1, 2, 3, 4), B(5, 6, 7, 8);
    // cout << "A + B = " << (A + B) << endl;
    // cout << "A * B = " << (A * B) << endl;
    cout << "(Implement Matrix2x2)" << endl;
}

// ============================================================
// MAIN
// ============================================================

int main() {
    cout << "=== Operator Overloading Exercises ===" << endl;
    
    cout << "\nEx1: Arithmetic" << endl;
    exercise1();
    
    cout << "\nEx2: Comparison" << endl;
    exercise2();
    
    cout << "\nEx3: Stream" << endl;
    exercise3();
    
    cout << "\nEx4: Subscript" << endl;
    exercise4();
    
    cout << "\nEx5: Function Call" << endl;
    exercise5();
    
    cout << "\nEx6: Increment" << endl;
    exercise6();
    
    cout << "\nEx7: Vector3D" << endl;
    exercise7();
    
    cout << "\nEx8: Matrix" << endl;
    exercise8();
    
    return 0;
}

// ============================================================
// ANSWERS
// ============================================================
/*
Ex1:
Fraction operator+(const Fraction& f) const { return Fraction(num*f.den + f.num*den, den*f.den); }
Fraction operator*(const Fraction& f) const { return Fraction(num*f.num, den*f.den); }

Ex2:
bool operator==(const Money& m) const { return cents == m.cents; }
bool operator<(const Money& m) const { return cents < m.cents; }
// Derive others from these

Ex3:
friend ostream& operator<<(ostream& os, const Rectangle& r) {
    return os << "Rectangle(" << r.width << " x " << r.height << ")";
}

Ex4:
int& operator[](size_t i) {
    if (i >= size) throw out_of_range("Index out of bounds");
    return data[i];
}

Ex5:
int operator()(int x) const {
    int result = 1;
    for (int i = 0; i < exponent; ++i) result *= x;
    return result;
}

Ex6:
Time& operator++() { ++minutes; normalize(); return *this; }
Time operator++(int) { Time t = *this; ++(*this); return t; }

Ex7:
Vector3D operator+(const Vector3D& v) const { return Vector3D(x+v.x, y+v.y, z+v.z); }
double operator*(const Vector3D& v) const { return x*v.x + y*v.y + z*v.z; }
friend ostream& operator<<(ostream& os, const Vector3D& v) {
    return os << "(" << v.x << ", " << v.y << ", " << v.z << ")";
}

Ex8:
Matrix2x2 operator+(const Matrix2x2& m) const {
    return Matrix2x2(data[0][0]+m.data[0][0], data[0][1]+m.data[0][1],
                     data[1][0]+m.data[1][0], data[1][1]+m.data[1][1]);
}
Matrix2x2 operator*(const Matrix2x2& m) const {
    return Matrix2x2(
        data[0][0]*m.data[0][0] + data[0][1]*m.data[1][0],
        data[0][0]*m.data[0][1] + data[0][1]*m.data[1][1],
        data[1][0]*m.data[0][0] + data[1][1]*m.data[1][0],
        data[1][0]*m.data[0][1] + data[1][1]*m.data[1][1]
    );
}
*/
Exercises - C++ Tutorial | DeepML