C++ 클래스 파일 분리(헤더파일,cpp파일,클래스.cpp파일)

Joosi_Cool·2022년 9월 23일
2

C++

목록 보기
8/20
post-thumbnail

🐣파일 분리

파일의 종류

1. 헤더파일 (Time.h)

#ifndef TIME_H
#define TIME_H

class Time
{
public:
	Time();
	void setTime(int, int, int);
	void printUniversal() const;
	void printStandard() const;

private:
	unsigned int hour;
	unsigned int mintute;
	unsigned int second;

};


#endif

이를 헤더파일에 선언하고 이 사이에 클래스를 설정해준다.
#ifndef TIME_H
#define TIME_H
~
#endif

  • #pragma once 도 가능

2. 클래스 정보가 들어간 .cpp파일 (Time.cpp)

#include<iostream>
#include<iomanip>
#include<stdexcept>
#include "Time.h"

using namespace std;


Time::Time()
	:hour(0), mintute(0), second(0)
{

}

void Time::setTime(int h, int m, int s)
{
	if ((h >= 0 && h < 24) && (m >= 0 && m < 60) && (s >= 0 && s < 60)) {
		hour = h;
		mintute = m;
		second = s;
	}
	else {
		throw invalid_argument(
			"hour,minute and/or second was out of range"
		);
	}

}

void Time::printUniversal() const
{
	cout << setfill('0') << setw(2) << hour << ":"
		<< setw(2) << mintute << ":" << setw(2) << second;
}

void Time::printStandard() const
{
	cout << ((hour == 0 || hour == 12) ? 12 : hour % 12) << ":"
		<< setfill('0') << setw(2) << mintute << ":" << setw(2)
		<< second << (hour < 12 ? "AM" : "PM") << endl;
}

여기에는 클래스에 대한 자세한 내용을 담는다.
#include "헤더파일명.h" 를 통해 헤더파일과 연결해주어야 한다.
또한 클래스에 대한 것을 사용할때 자료형 + 클래스 명:: 멤버함수로 정의 해야한다.
ex) void Time::printStandard() {}

3. 메인 함수

#include<iostream>
#include<stdexcept>
#include "Time.h"
using namespace std;

int main()
{
	Time t;

	cout << "The initial universal time is ";
	t.printStandard();

	try
	{
		t.setTime(99, 99, 99);
	}
	catch (invalid_argument& e)
	{
		cout << "Exception" << e.what() << endl;
	}

}

이 곳에선 앞에서 선언한 클래스를 사용한다.
앞 파일과 마찬가지로 헤더파일을 include 해주어야 한다.
그리고 나선 클래스 사용하던대로 사용하면 된다.

profile
집돌이 FE개발자의 노트

0개의 댓글