Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Class Composition, Inheritance, Template Classes, and Standard Library in C++

Tech Nov 25 14

Task 1

task1.cpp

#include <iostream>

using std::cout;
using std::endl;

class A {
public:
    A(int x0, int y0);
    void display() const;

private:
    int x, y;
};

A::A(int x0, int y0) : x{x0}, y{y0} {}

void A::display() const {
    cout << x << ", " << y << endl;
}

class B {
public:
    B(double x0, double y0);
    void display() const;

private:
    double x, y;
};

B::B(double x0, double y0) : x{x0}, y{y0} {}

void B::display() const {
    cout << x << ", " << y << endl;
}

void test() {
    cout << "Testing Class A: " << endl;
    A a(3, 4);
    a.display();

    cout << "\nTesting Class B: " << endl;
    B b(3.2, 5.6);
    b.display();
}

int main() {
    test();
}

task2.cpp

#include <iostream>
#include <string>

using std::cout;
using std::endl;
using std::string;

template<typename T>
class X {
public:
    X(T x0, T y0);
    void display();

private:
    T x, y;
};

template<typename T>
X<T>::X(T x0, T y0) : x{x0}, y{y0} {}

template<typename T>
void X<T>::display() {
    cout << x << ", " << y << endl;
}

void test() {
    cout << "Test 1: Template class X instantiated with int" << endl;
    X<int> x1(3, 4);
    x1.display();

    cout << endl;

    cout << "Test 2: Template class X instantiated with double" << endl;
    X<double> x2(3.2, 5.6);
    x2.display();

    cout << endl;

    cout << "Test 3: Template class X instantiated with string" << endl;
    X<string> x3("hello", "oop");
    x3.display();
}

int main() {
    test();
}

Task 2

GradeCalc.hpp

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <numeric>
#include <iomanip>

using std::vector;
using std::string;
using std::cin;
using std::cout;
using std::endl;

class GradeCalc : public vector<int> {
public:
    GradeCalc(const string &cname, int size);
    void input();
    void output() const;
    void sort(bool ascending = false);
    int min() const;
    int max() const;
    float average() const;
    void info();

private:
    void compute();

private:
    string course_name;
    int n;
    vector<int> counts = vector<int>(5, 0);
    vector<double> rates = vector<double>(5, 0);
};

GradeCalc::GradeCalc(const string &cname, int size) : course_name{cname}, n{size} {}

void GradeCalc::input() {
    int grade;
    for (int i = 0; i < n; ++i) {
        cin >> grade;
        this->push_back(grade);
    }
}

void GradeCalc::output() const {
    for (auto ptr = this->begin(); ptr != this->end(); ++ptr)
        cout << *ptr << " ";
    cout << endl;
}

void GradeCalc::sort(bool ascending) {
    if (ascending)
        std::sort(this->begin(), this->end());
    else
        std::sort(this->begin(), this->end(), std::greater<int>());
}

int GradeCalc::min() const {
    return *std::min_element(this->begin(), this->end());
}

int GradeCalc::max() const {
    return *std::max_element(this->begin(), this->end());
}

float GradeCalc::average() const {
    return std::accumulate(this->begin(), this->end(), 0) * 1.0 / n;
}

void GradeCalc::compute() {
    for (int grade : *this) {
        if (grade < 60)
            counts.at(0)++;
        else if (grade >= 60 && grade < 70)
            counts.at(1)++;
        else if (grade >= 70 && grade < 80)
            counts.at(2)++;
        else if (grade >= 80 && grade < 90)
            counts.at(3)++;
        else if (grade >= 90)
            counts.at(4)++;
    }

    for (int i = 0; i < rates.size(); ++i)
        rates.at(i) = counts.at(i) * 1.0 / n;
}

void GradeCalc::info() {
    cout << "Course Name:\t" << course_name << endl;
    cout << "Sorted Grades:\t";
    sort();
    output();
    cout << "Maximum:\t" << max() << endl;
    cout << "Minimum:\t" << min() << endl;
    cout << "Average:\t" << std::fixed << std::setprecision(2) << average() << endl;

    compute();

    vector<string> tmp{"[0, 60)  ", "[60, 70)", "[70, 80)", "[80, 90)", "[90, 100]"};
    for (int i = tmp.size() - 1; i >= 0; --i)
        cout << tmp[i] << "\t: " << counts[i] << " students\t"
             << std::fixed << std::setprecision(2) << rates[i] * 100 << "%" << endl;
}

task2.cpp

#include "GradeCalc.hpp"
#include <iomanip>

void test() {
    int n;
    cout << "Enter number of students: ";
    cin >> n;

    GradeCalc c1("OOP", n);

    cout << "Input grades: " << endl;
    c1.input();
    cout << "Output grades: " << endl;
    c1.output();

    cout << string(20, '*') + "Course Grade Information" + string(20, '*') << endl;
    c1.info();
}

int main() {
    test();
}

Questions:

  1. Grades are stored in vector<int> member grade. Access to individual grades is done through the this pointer. The input function uses the standard library's push_back interface to store data.
  2. Line 68 computes the average. Removing * 1.0 would result in an integer result. Multiplying by 1.0 converts it to a float, yielding a decimal result.
  3. Potential issues: Operating on an empty data set could lead to errors.

Task 3

GradeCalc.hpp

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <numeric>
#include <iomanip>

using std::vector;
using std::string;
using std::cin;
using std::cout;
using std::endl;

class GradeCalc {
public:
    GradeCalc(const string &cname, int size);
    void input();
    void output() const;
    void sort(bool ascending = false);
    int min() const;
    int max() const;
    float average() const;
    void info();

private:
    void compute();

private:
    string course_name;
    int n;
    vector<int> grades;
    vector<int> counts = vector<int>(5, 0);
    vector<double> rates = vector<double>(5, 0);
};

GradeCalc::GradeCalc(const string &cname, int size) : course_name{cname}, n{size} {}

void GradeCalc::input() {
    int grade;
    for (int i = 0; i < n; ++i) {
        cin >> grade;
        grades.push_back(grade);
    }
}

void GradeCalc::output() const {
    for (int grade : grades)
        cout << grade << " ";
    cout << endl;
}

void GradeCalc::sort(bool ascending) {
    if (ascending)
        std::sort(grades.begin(), grades.end());
    else
        std::sort(grades.begin(), grades.end(), std::greater<int>());
}

int GradeCalc::min() const {
    return *std::min_element(grades.begin(), grades.end());
}

int GradeCalc::max() const {
    return *std::max_element(grades.begin(), grades.end());
}

float GradeCalc::average() const {
    return std::accumulate(grades.begin(), grades.end(), 0) * 1.0 / n;
}

void GradeCalc::compute() {
    for (int grade : grades) {
        if (grade < 60)
            counts.at(0)++;
        else if (grade >= 60 && grade < 70)
            counts.at(1)++;
        else if (grade >= 70 && grade < 80)
            counts.at(2)++;
        else if (grade >= 80 && grade < 90)
            counts.at(3)++;
        else if (grade >= 90)
            counts.at(4)++;
    }

    for (int i = 0; i < rates.size(); ++i)
        rates.at(i) = counts.at(i) * 1.0 / n;
}

void GradeCalc::info() {
    cout << "Course Name:\t" << course_name << endl;
    cout << "Sorted Grades:\t";
    sort();
    output();
    cout << "Maximum:\t" << max() << endl;
    cout << "Minimum:\t" << min() << endl;
    cout << "Average:\t" << std::fixed << std::setprecision(2) << average() << endl;

    compute();

    vector<string> tmp{"[0, 60)  ", "[60, 70)", "[70, 80)", "[80, 90)", "[90, 100]"};
    for (int i = tmp.size() - 1; i >= 0; --i)
        cout << tmp[i] << "\t: " << counts[i] << " students\t"
             << std::fixed << std::setprecision(2) << rates[i] * 100 << "%" << endl;
}

task3.cpp

#include "GradeCalc.hpp"
#include <iomanip>

void test() {
    int n;
    cout << "Enter number of students: ";
    cin >> n;

    GradeCalc c1("OOP", n);

    cout << "Input grades: " << endl;
    c1.input();
    cout << "Output grades: " << endl;
    c1.output();

    cout << string(20, '*') + "Course Grade Information" + string(20, '*') << endl;
    c1.info();
}

int main() {
    test();
}

Questions:

  1. Grades are stored in vector<int> member grades. Sorting uses iterators grades.begin() and grades.end(). Output accesses grades via a for loop.
  2. While the class's logic and interface remain unchanged, internal details can be modified. Both encapsulation and inheritance can achieve this.

Task 4

task4_1.cpp

#include <iostream>
#include <string>
#include <limits>

using namespace std;

void test1() {
    string s1, s2;
    cin >> s1 >> s2;
    cout << "s1: " << s1 << endl;
    cout << "s2: " << s2 << endl;
}

void test2() {
    string s1, s2;
    getline(cin, s1);
    getline(cin, s2);
    cout << "s1: " << s1 << endl;
    cout << "s2: " << s2 << endl;
}

void test3() {
    string s1, s2;
    getline(cin, s1, ' ');
    getline(cin, s2);
    cout << "s1: " << s1 << endl;
    cout << "s2: " << s2 << endl;
}

int main() {
    cout << "Test 1: Using cin to read strings" << endl;
    test1();
    cout << endl;

    cin.ignore(numeric_limits<streamsize>::max(), '\n');

    cout << "Test 2: Using getline() to read strings" << endl;
    test2();
    cout << endl;

    cout << "Test 3: Using getline() with a custom delimiter" << endl;
    test3();
}

Question:

Line 35's purpose is to clear the current line. Without it, getline in test2 would read the leftover '\n' as the first string, so s1 would be '\n'.

task4_2.cpp

#include <iostream>
#include <string>
#include <vector>
#include <limits>

using namespace std;

void output(const vector<string> &v) {
    for (auto &s : v)
        cout << s << endl;
}

void test() {
    int n;
    while (cout << "Enter n: ", cin >> n) {
        vector<string> v1;

        for (int i = 0; i < n; ++i) {
            string s;
            cin >> s;
            v1.push_back(s);
        }

        cout << "output v1: " << endl;
        output(v1);
        cout << endl;
    }
}

int main() {
    cout << "Test: Reading multiple strings with cin" << endl;
    test();
}

task4_3.cpp

#include <iostream>
#include <string>
#include <vector>
#include <limits>

using namespace std;

void output(const vector<string> &v) {
    for (auto &s : v)
        cout << s << endl;
}

void test() {
    int n;
    while (cout << "Enter n: ", cin >> n) {
        cin.ignore(numeric_limits<streamsize>::max(), '\n');

        vector<string> v2;

        for (int i = 0; i < n; ++i) {
            string s;
            getline(cin, s);
            v2.push_back(s);
        }
        cout << "output v2: " << endl;
        output(v2);
        cout << endl;
    }
}

int main() {
    cout << "Test: Reading multiple strings with getline()" << endl;
    test();
}

Question:

Line 16's purpose is to clear the current line. Without it, the first string in container v2 would be '\n'.

Task 5

grm.hpp

#include <bits/stdc++.h>
using namespace std;

template<typename T>
class GameResourceManager {
public:
    GameResourceManager(T x0) : resource(x0) {}
    T get() {
        return resource;
    }
    void update(T change) {
        resource += change;
        if (resource < 0) {
            resource = 0;
        }
    }

private:
    T resource;
};

task5.cpp

#include "grm.hpp"
#include <iostream>

using std::cout;
using std::endl;

void test1() {
    GameResourceManager<float> HP_manager(99.99);
    cout << "Current Health: " << HP_manager.get() << endl;
    HP_manager.update(9.99);
    cout << "After adding 9.99 Health, current Health: " << HP_manager.get() << endl;
    HP_manager.update(-999.99);
    cout << "After subtracting 999.99 Health, current Health: " << HP_manager.get() << endl;
}

void test2() {
    GameResourceManager<int> Gold_manager(100);
    cout << "Current Gold: " << Gold_manager.get() << endl;
    Gold_manager.update(50);
    cout << "After adding 50 Gold, current Gold: " << Gold_manager.get() << endl;
    Gold_manager.update(-99);
    cout << "After subtracting 99 Gold, current Gold: " << Gold_manager.get() << endl;
}

int main() {
    cout << "Test 1: Instantiating GameResourceManager with float" << endl;
    test1();
    cout << endl;

    cout << "Test 2: Instantiating GameResourceManager with int" << endl;
    test2();
}

Task 6

info.hpp

#include <bits/stdc++.h>
using namespace std;

class info {
public:
    info(const string &nickname, const string &contact, const string &city, int n)
        : nickname(nickname), contact(contact), city(city), n(n) {}

    void display() const {
        cout << "Nickname: " << nickname << endl;
        cout << "Contact: " << contact << endl;
        cout << "City: " << city << endl;
        cout << "Number of participants: " << n << endl;
    }

private:
    string nickname;
    string contact;
    string city;
    int n;
};

task6.cpp

#include "info.hpp"
#include <bits/stdc++.h>
using namespace std;

int main() {
    const int capacity = 100;
    vector<info> audience_list;
    string nickname, contact, city;
    int n, num = 0;
    char t;

    while (true) {
        if (num >= capacity) {
            cout << "Maximum capacity reached, registration closed." << endl;
            break;
        }

        cout << "Nickname: ";
        getline(cin, nickname);
        cout << "Contact: ";
        getline(cin, contact);
        cout << "City: ";
        getline(cin, city);
        cout << "Number of participants: ";
        cin >> n;

        if (num + n > capacity) {
            cout << "Exceeds capacity. Enter 'q' to quit or 'u' to update: ";
            string s;
            cin >> s;
            cin.ignore();
            if (s == "q")
                continue;
            else if (s == "u") {
                cout << "Re-enter number of participants: ";
                cin >> n;
                cin.ignore();
            }
        }

        info new_info(nickname, contact, city, n);
        audience_list.push_back(new_info);
        num += n;

        cin.ignore();
    }

    cout << "Registered audience information:" << endl;
    for (const auto &info : audience_list) {
        info.display();
        cout << "------------------------------" << endl;
    }

    return 0;
}

Task 7

account.h

#pragma once
#ifndef ACCOUNT_H
#define ACCOUNT_H

#include "date.h"
#include "accumulator.h"
#include <string>

class Account {
private:
    std::string id;
    double balance;
    static double total;

protected:
    Account(const Date &date, const std::string &id);
    void record(const Date &date, double amount, const std::string &desc);
    void error(const std::string &msg) const;

public:
    const std::string &getId() const { return id; }
    double getBalance() const { return balance; }
    static double getTotal() { return total; }

    void show() const;
};

class SavingsAccount : public Account {
private:
    Accumulator acc;
    double rate;

public:
    SavingsAccount(const Date &date, const std::string &id, double rate);
    double getRate() const { return rate; }

    void deposit(const Date &date, double amount, const std::string &desc);
    void withdraw(const Date &date, double amount, const std::string &desc);
    void settle(const Date &date);
};

class CreditAccount : public Account {
private:
    Accumulator acc;
    double credit;
    double rate;
    double fee;

    double getDebt() const {
        double balance = getBalance();
        return (balance < 0 ? balance : 0);
    }

public:
    CreditAccount(const Date &date, const std::string &id, double credit, double rate, double fee);
    double getCredit() const { return credit; }
    double getRate() const { return rate; }
    double getAvailableCredit() const {
        if (getBalance() < 0)
            return credit + getBalance();
        else
            return credit;
    }

    void deposit(const Date &date, double amount, const std::string &desc);
    void withdraw(const Date &date, double amount, const std::string &desc);
    void settle(const Date &date);
    void show() const;
};

#endif // ACCOUNT_H

accumulator.h

#pragma once
#ifndef ACCUMULATOR_H
#define ACCUMULATOR_H

#include "date.h"

class Accumulator {
private:
    Date lastDate;
    double value;
    double sum;

public:
    Accumulator(const Date &date, double value) : lastDate(date), value(value), sum{0} {}

    double getSum(const Date &date) const {
        return sum + value * date.distance(lastDate);
    }

    void change(const Date &date, double value) {
        sum = getSum(date);
        lastDate = date;
        this->value = value;
    }

    void reset(const Date &date, double value) {
        lastDate = date;
        this->value = value;
        sum = 0;
    }
};

#endif // ACCUMULATOR_H

account.cpp

#include "account.h"
#include <cmath>
#include <iostream>

using namespace std;

double Account::total = 0;

Account::Account(const Date &date, const string &id) : id{id}, balance{0} {
    date.show();
    cout << "\t#" << id << " created" << endl;
}

void Account::record(const Date &date, double amount, const string &desc) {
    amount = floor(amount * 100 + 0.5) / 100;
    balance += amount;
    total += amount;
    date.show();
    cout << "\t#" << id << "\t" << amount << "\t" << balance << "\t" << desc << endl;
}

void Account::show() const {
    cout << id << "\tBalance:" << balance;
}

void Account::error(const string &msg) const {
    cout << "Error(#" << id << "):" << msg << endl;
}

SavingsAccount::SavingsAccount(const Date &date, const string &id, double rate)
    : Account(date, id), rate(rate), acc(date, 0) {}

void SavingsAccount::deposit(const Date &date, double amount, const string &desc) {
    record(date, amount, desc);
    acc.change(date, getBalance());
}

void SavingsAccount::withdraw(const Date &date, double amount, const string &desc) {
    if (amount > getBalance()) {
        error("not enough money");
    } else {
        record(date, -amount, desc);
        acc.change(date, getBalance());
    }
}

void SavingsAccount::settle(const Date &date) {
    double interest = acc.getSum(date) * rate / date.distance(Date(date.getYear() - 1, 1, 1));
    if (interest != 0)
        record(date, interest, "interest");
    acc.reset(date, getBalance());
}

CreditAccount::CreditAccount(const Date &date, const string &id, double credit, double rate, double fee)
    : Account(date, id), credit(credit), rate(rate), fee(fee), acc(date, 0) {}

void CreditAccount::deposit(const Date &date, double amount, const string &desc) {
    record(date, amount, desc);
    acc.change(date, getDebt());
}

void CreditAccount::withdraw(const Date &date, double amount, const string &desc) {
    if (amount - getBalance() > credit) {
        error("not enough credit");
    } else {
        record(date, -amount, desc);
        acc.change(date, getDebt());
    }
}

void CreditAccount::settle(const Date &date) {
    double interest = acc.getSum(date) * rate;
    if (interest != 0)
        record(date, interest, "interest");
    if (date.getMonth() == 1)
        record(date, -fee, "annual fee");
    acc.reset(date, getDebt());
}

void CreditAccount::show() const {
    Account::show();
    cout << "\tAvailable credit:" << getAvailableCredit();
}

date.cpp

#include "date.h"
#include <iostream>
#include <cstdlib>

using namespace std;

namespace {
    const int DAYS_BEFORE_MONTH[] = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};
}

Date::Date(int year, int month, int day) : year{year}, month{month}, day{day} {
    if (day <= 0 || day > getMaxDay()) {
        cout << "Invalid date:";
        show();
        cout << endl;
        exit(1);
    }

    int years = year - 1;
    totalDays = years * 365 + years / 4 - years / 100 + years / 400 + DAYS_BEFORE_MONTH[month - 1] + day;
    if (isLeapYear() && month > 2)
        totalDays++;
}

int Date::getMaxDay() const {
    if (isLeapYear() && month == 2)
        return 29;
    else
        return DAYS_BEFORE_MONTH[month] - DAYS_BEFORE_MONTH[month - 1];
}

void Date::show() const {
    cout << getYear() << "-" << getMonth() << "-" << getDay();
}

date.h

#pragma once
#ifndef DATE_H
#define DATE_H

class Date {
private:
    int year;
    int month;
    int day;
    int totalDays;

public:
    Date(int year, int month, int day);
    int getYear() const { return year; }
    int getMonth() const { return month; }
    int getDay() const { return day; }
    int getMaxDay() const;
    bool isLeapYear() const {
        return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
    }
    void show() const;
    int distance(const Date &date) const {
        return totalDays - date.totalDays;
    }
};

#endif // DATE_H

task7.cpp

#include "account.h"
#include <iostream>

using namespace std;

int main() {
    Date date(2008, 11, 1);
    SavingsAccount sa1(date, "S3755217", 0.015);
    SavingsAccount sa2(date, "02342342", 0.015);
    CreditAccount ca(date, "C5392394", 10000, 0.0005, 50);

    sa1.deposit(Date(2008, 11, 5), 5000, "salary");
    ca.withdraw(Date(2008, 11, 15), 2000, "buy a cell");
    sa2.deposit(Date(2008, 11, 25), 10000, "sell stock 0323");

    ca.settle(Date(2008, 12, 1));

    ca.deposit(Date(2008, 12, 1), 2016, "repay the credit");
    sa1.deposit(Date(2008, 12, 5), 5500, "salary");

    sa1.settle(Date(2009, 1, 1));
    sa2.settle(Date(2009, 1, 1));
    ca.settle(Date(2009, 1, 1));

    cout << endl;
    sa1.show();
    cout << endl;
    sa2.show();
    cout << endl;
    ca.show();
    cout << endl;
    cout << "Total:" << Account::getTotal() << endl;

    return 0;
}
Tags: C++

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.