// 맨 위에
#ifndef MY_CLASS_H
#define MY_CLASS_H
// 맨 밑에
#endif
#ifndef MY_CLASS_H // MyClass.h 파일이 여러군데에서 사용될 때 컴파일 한번만 해라~
#define MY_CLASS_H
// TODO: 새로운 멤버 함수 추가해보기 연습
class MyClass
{
public: // 멤버 함수 정의만하고, 함수 정의만 하고, 코드는 .cpp 에 하기
MyClass(); // 멤버 함수의 몸체(body) 모두 삭제, 깔끔
MyClass(int number);
~MyClass();
void Increment(int a);
// void Decrement(int a); // 구현 실습
void Print();
private:
int number_ = 0; // 초기값
};
#endif // MY_CLASS_H
#include "MyClass.h" // 선언 헤더 꼭 include
#include <iostream>
using namespace std; // 보통 .h 파일 대신 .cpp에 사용
MyClass::MyClass()
{
// 호출 시점 확인
cout << "MyClass()" << endl;
}
MyClass::MyClass(int number) // init_str이 유효한 메모리라고 가정
{
cout << "MyClass(int number)" << endl;
// this pointer 소개
this->number_ = number;
}
MyClass::~MyClass()
{
// 호출 시점 확인
cout << "~MyClass()" << endl;
}
void MyClass::Increment(int a)
{
number_ += a;
}
void MyClass::Print()
{
cout << number_ << endl;
}
#include <iostream>
#include <cstring>
#include "MyClass.h" // <- 설명
using namespace std;
int main() // 메인 함수만 작성
{
MyClass my_class1;
MyClass my_class2(123);
my_class1.Print();
my_class2.Print();
my_class1.Increment(1);
my_class1.Print();
// 배열 사용 가능
// 포인터 사용 가능 등 안내
// 기본 자료형과 비교
return 0;
}
출처 : 홍정모 유튜브