2017년 5월 23일 화요일

[C++] MyString Sample Codes (May 23)

#include <iostream>
#include <string>
#include <cstring>

using namespace std;

class MyString {

public:
    // char* Buffer;
    string Buffer;

public:
    // constructor
    MyString(string mystring) {
        cout << "Constructor: creating new MyString" << endl;
        Buffer = mystring;
        cout << "Buffer points to: 0x" << (void *)&Buffer[0] << endl;
    }


    /*
    MyString(const char* mystring) {
        if (mystring != NULL) {
            Buffer = new char [strlen(mystring) + 1];
            strcpy(Buffer, mystring);

            // Display memory address pointed by local buffer
            cout << "Buffer points to: 0x" << hex;
            cout << (unsigned int*)Buffer << endl;
        }
        else
            Buffer = NULL;
    }

    // Copy Constructor
    MyString(const MyString& CopySource) {
        cout << "Copy Constructor" << endl;
        if (CopySource.Buffer != NULL) {
            Buffer = new char[strlen(CopySource.Buffer) + 1];
            strcpy(Buffer, CopySource.Buffer);

            cout << "CopySource Buffer points to: 0x" << hex;
            cout << (unsigned int*)CopySource.Buffer << endl;

            cout << "Buffer points to: 0x" << hex;
            cout << (unsigned int*)Buffer << endl;
        }
    }
*/
    ~MyString() {

        cout << "Invoking destructor" << endl;

        /*
        if (Buffer != NULL)
            delete [] Buffer;
        */
    }
/*
    const char* GetString() {
        return Buffer;
    }

    int GetLength() {
        return strlen(Buffer);
    }
*/
};

void UseMyString(MyString Input)
{
    cout << "UseMyString Buffer points to : 0x" << (void *)&Input.Buffer[0] << endl;
    cout << "length: " << Input.Buffer.length();
    cout << "Buffer contains: " << Input.Buffer.c_str() << endl;

    return;
}

int main()
{

    MyString SayHello("SayHello from the class");

    UseMyString(SayHello);

    // cout << SayHello.GetString() << endl;

    return 0;
}