2017년 5월 18일 목요일

[C++] Source codes we worked on May 18

#include <iostream>
#include <string>
#include <sstream>   // string stream
#include <memory>   // Include memory to use std::unique_ptr

using namespace std;

template <typename T>
class smart_pointer {
private:
    T* m_pRawPointer;
public:
    // Construcotr
    smart_pointer(T* pData) : m_pRawPointer(pData) {};
    // Destructor
    ~smart_pointer() {
        cout << "Smart pointer destructor is invoked" << endl;
        delete m_pRawPointer;
    }
    // Operator *
    T& operator* () const {
        return *(m_pRawPointer);
    }
    // Operator ->
    T* operator-> () const {
        return m_pRawPointer;
    }
};

class Date {
private:
    int Day;
    int Month;
    int Year;

    string DateString; // class

public:
    Date (int D, int M, int Y)
        : Day(D), Month(M), Year(Y) {};

    Date operator - (int DaystoSub) {

        return Date(Day - DaystoSub, Month, Year);

    }

    // Implement Conversion operator const char *
    operator const char*() {
        ostringstream formattedDate;

        formattedDate << Day << "/" << Month << "/" << Year;

        DateString = formattedDate.str();
        return DateString.c_str();
    }

    void DisplayDate() {
        cout <<  Day << "/" << Month << "/" << Year;
    }
};

int main()
{
    Date today(18, 5, 2017);
    Date yesterday(today - 1);

   //  yesterday = today - 1;
    cout << yesterday << endl;

    /*
    cout << "Today is on: " << today << endl;
    // smart pointer
    // supports automatic deallocation() , which means delete (in C++)
    // Actually, delete implies free() in C language
    smart_pointer<int> pDynamicAllocInteger(new int);
    *pDynamicAllocInteger = 42;

    cout << *pDynamicAllocInteger << endl;

    // local variable => stack => automatically poped (removed) when main() returns
    // The destructor is invoked automatically
    // That's why it is called smart_pointer
    // How can we verify this?
    smart_pointer<Date> tomorrow(new Date(19, 5, 2017));
    tomorrow->DisplayDate();
    */
    return 0;
}