C++2010. 6. 22. 10:52

클래스를 헤더파일과 구현 파일에 나누어 담는 방법을 배워보자. 우선은 point 클래스의 최종 소스코드를 보자.

소스코드가 딱 봐도 복잡하기 때문에 나누어 담아주는 것이 좋다.

#include <iostream>
using namespace std;

class point
{
public:
  void print();

  point();
  point(int initialx, int initialy);
  point(const point& pt);

  void setx(int value)
  {
    if(value < 0)      x = 0;
    else if(value > 100)  x = 100;
    else          x = value;
  }

  void sety(int value)
  {
    if(value < 0)      y = 0;
    else if(value > 100)  y = 100;
    else          y = value;
  }
  int getx()  {return x;};
  int gety()  {return y;};

private:
  int x;
  int y;
};

point::point(const point& pt)
{
  x = pt.x;
  y = pt.y;
}
point::point(int initialx, int initialy)
{
  setx(initialx);
  sety(initialy);
}
point::point()
{
  x = 0;
  y = 0;
}
void point::print()
{
  cout<< "( " << x << ", " << y << ")\n";
}

int main()
{
  point pt(-50,200);

  pt.print();
  
  return 0;
}

위의 코드를 다음과 같이 3개의 파일로 나누어 작성해보자.

point.h - 클래스 정의 헤더파일

point.cpp - 클래스 멈버구현

main.cpp - main함수 구현

<point.h>

#ifndef POINT_H
#define POINT_H

class point
{
public:
  void print();
  
  point();
  point(int initialx, int initialy);
  point(const point& pt);
  
  void setx(int value)
  {
    if(value < 0)      x = 0;
    else if(value > 100)  x = 100;
    else          x = value;
  }
  
  void sety(int value)
  {
    if(value < 0)      y = 0;
    else if(value > 100)  y = 100;
    else          y = value;
  }
  int getx()  {return x;};
  int gety()  {return y;};
  
private:
  int x;
  int y;
};
#endif

<point.cpp>

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

using namespace std;

point::point(const point& pt)
{
  x = pt.x;
  y = pt.y;
}
point::point(int initialx, int initialy)
{
  setx(initialx);
  sety(initialy);
}
point::point()
{
  x = 0;
  y = 0;
}
void point::print()
{
  cout<< "( " << x << ", " << y << ")\n";
}

<main.c>

#include "point.h"

int main()
{
  point pt(-50,200);
  
  pt.print();
  
  return 0;
}

이렇게 나누면 다음과 훨씬 코드가 간결해져서 읽기가 편해진다.

파일을 나눌때 주의해야 할 점은 point.h파일에서와 같이 처음부분에 #ifndef POINT.H와 #define POINT.H 그리고 마지막줄에 #endif를 추가해줘야한다.

ifndef의 역할은 헤더파일이 겹치는 것을 막는 일종의 매크로이다. 




Posted by 해해해해해해해해