배우고픈 공돌이

C를 C++로 변경하기. (2) 본문

C, C++ /C++

C를 C++로 변경하기. (2)

내 마음 아홉수 2017. 10. 12. 11:47

3. malloc - free -> new - delete


void Stack::initStack(int size)

{

//this-> pArr = (int*) malloc(sizeof(int)*size);

this-> pArr = new int[size];

}


void Stack::cleanupStack()

{

//free( this->pArr );

delete [] this->pArr;

}


4. init, close function -> using constructor, destructor


-main.cpp


int main()

{

  //initStack(&s1,10); initStack(&s2,100);

s1.Stack(10);

  s2.Stack(100);


  //cleanupStack(&s1); cleanupStack(&s2);

  //auto destruct before return.

  return 0;

}


-stack.h


struct Stack{

Stack(int size); //void initStack(int size);  . constructor

~Stack(); //void cleanupStack();     . destructor

};


- struct.cpp


Stack::Stack(int size) // void Stack::initStack

{

}


Stack::~Stack() //void Stack::cleanupStack

{

}


5, 6. information hiding, struct -> class


class Stack{

private:

int* pArr;

int  tos;

int  size;

public:

Stack(int size);

~Stack();

void push(int data);

int pop();

};


7, 8. c header -> c++ header adapt namespace, using iostream instead cstdio 


* include <header.h> -->  include <cheader>


-main.cpp


#include <iostream> // #include <cstdio>


-stack.cpp


#include <cassert> // #include<assert.h>


최종본.


-main.cpp


#include <iostream>

#include "stack.h"


int main()

{

Stack s1(10), s2(100);


s1.push(100); s1.push(200); s1.push(300);

s2.push(900); s2.push(800); s2.push(700);

std::cout << "s1 1st pop() : " << s1.pop() << std::endl;

std::cout << "s1 2nd pop() : " << s1.pop() << std::endl;

std::cout << "s1 3rd pop() : " << s1.pop() << std::endl;


std::cout << "s2 1st pop() : " << s2.pop() << std::endl;

std::cout << "s2 2nd pop() : " << s2.pop() << std::endl;

std::cout << "s2 3rd pop() : " << s2.pop() << std::endl;


return 0;

}


-stack.h


#ifndef STACK_H

#define STACK_H


class Stack{

private: //information hiding

int* pArr;

int  tos;

int  size;

public:

Stack(int size); //void initStack(int size);

~Stack(); //void cleanupStack();

void push(int data);

int pop();

};


#endif


-stack.cpp


#include "stack.h"

#include <cassert>


Stack::Stack(int size)

{

//this-> pArr = (int*) malloc(sizeof(int)*size);

this-> pArr = new int[size];

assert( this->pArr );


this-> size = size;

this-> tos = 0;

}


Stack::~Stack()

{

//free( this->pArr );

delete [] this->pArr;

}


void Stack::push(int data)

{

assert( this->tos != this->size);

this->pArr[(this->tos)++] = data;

}


int Stack::pop()

{

assert( this->tos != 0 );

return this->pArr[--(this->tos)];

}



'C, C++ > C++' 카테고리의 다른 글

c++ reference!  (0) 2017.10.16
C++ linked list!  (0) 2017.10.16
C++ Queue!  (0) 2017.10.16
C++ stack!  (0) 2017.10.16
C를 C++로 변경하기.  (0) 2017.10.12
Comments