배우고픈 공돌이

C를 C++로 변경하기. 본문

C, C++ /C++

C를 C++로 변경하기.

내 마음 아홉수 2017. 10. 12. 10:38

c로된 코드를 c++로 변경하기 위해 8단계 정도로 나눠볼 수 있다.


1. .c -> .cpp


gcc 컴파일러를 이용하여 .c파일을 컴파일 했다면, 


.c파일을 .cpp파일로 확장자 변경하고 g++ 컴파일러를 사용하면 컴파일 된다.



2. 함수 -> 구조체변수(객체)의 멤버함수로 변경


아래의 c코드를 예를 들어 변경한다.


-main.c


#include <stdio.h>

#include "stack.h"


int main(void)

{

stack_t s1, s2;


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


push(&s1,100); push(&s1,200); push(&s1,300);

push(&s2,900); push(&s2,800); push(&s2,700);

printf("s1 1st pop : %d \n",pop(&s1));

printf("s1 2nd pop : %d \n",pop(&s1));

printf("s1 3rd pop : %d \n",pop(&s1));


printf("s2 1st pop : %d \n",pop(&s2));

printf("s2 2nd pop : %d \n",pop(&s2));

printf("s2 3rd pop : %d \n",pop(&s2));

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


return 0;

}


-stack.h


#ifndef STACK_H

#define STACK_H


typedef struct {

int* pArr;

int  tos;

int  size;

} stack_t;


void initStack(stack_t* s, int size);

void cleanupStack(stack_t* s);

void push(stack_t* s, int data);

int pop(stack_t* s);


#endif


-stack.c

#include "stack.h"
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>

void initStack(stack_t* s, int size)
{
s -> pArr = (int*) malloc(sizeof(int)*size);
assert( s->pArr );

s -> size = size;
s -> tos = 0;
}

void cleanupStack(stack_t* s)
{
free( s->pArr );
}

void push(stack_t* s,int data)
{
assert( s->tos != s->size);
s->pArr[(s->tos)++] = data;
}

int pop(stack_t* s)
{
assert( s->tos != 0 );
return s->pArr[--(s->tos)];
}

-main.cpp


#include <stdio.h>

#include "stack.h"


int main(void)

{

stack_t s1, s2;


s1.initStack(10); s2.initStack(100);


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

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

printf("s1 1st pop : %d \n",s1.pop());

printf("s1 2nd pop : %d \n",s1.pop());

printf("s1 3rd pop : %d \n",s1.pop());


printf("s2 1st pop : %d \n",s2.pop());

printf("s2 2nd pop : %d \n",s2.pop());

printf("s2 3rd pop : %d \n",s2.pop());

s1.cleanupStack(); s2.cleanupStack();


return 0;

}


-stack.h


#ifndef STACK_H

#define STACK_H


struct Stack {

int* pArr;

int  tos;

int  size;

  void initStack(stack_t* s, int size);

  void cleanupStack(stack_t* s);

  void push(stack_t* s, int data);

  int pop(stack_t* s); 

};


#endif


-stack.cpp

#include "stack.h"
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>

void Stack::initStack(int size)
{
this-> pArr = (int*) malloc(sizeof(int)*size);
assert( this->pArr );

this-> size = size;
this-> tos = 0;
}

void Stack::cleanupStack()
{
free( 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++로 변경하기. (2)  (0) 2017.10.12
Comments