Class
- 추상화, 캡슐화, 상속, 다형성 즉 객체 지향의 4가지 주요 원칙을 구현하는 기본 단위이다.
- 동일한 구조와 기능을 가진 여러 객체를 효율적으로 생성하고 관리할 수 있게 한다.
#include <iostream>
using namespace std;
class Student
{
public:
// 동작 함수 정의
double GetAverage();
int GetMaxScore();
void SetKorScore(int Kor)
{
this->Kor = Kor;
}
void SetMathScore(int Math)
{
this->Math = Math;
}
void SetEngScore(int Eng)
{
this->Eng = Eng;
}
int GetKorScore() { return Kor; }
int GetMathScore() { return Math; }
int GetEngScore() { return Eng; }
private:
// 멤버 변수 정의
int Kor;
int Math;
int Eng;
};
double Student::GetAverage()
{
return Kor + Math + Eng / 3.0f;
}
int Student::GetMaxScore()
{
return max({ Kor,Math,Eng });
}
int main()
{
Student s;
s.SetKorScore(50);
s.SetMathScore(60);
s.SetEngScore(100);
cout << "과목 중 제일 높은 점수: " << s.GetMaxScore() << endl;
cout << "전체 과목 평균: " << s.GetAverage();
return 0;
}
변수의 데이터는 직접적으로 접근해서 제어하였을 때, 오류가 발생하거나 타인이 임의로 조작할 수 있기 때문에 private 접근 제어 지정자로 설정하였고, 이 변수 데이터를 바탕으로 동작하는 기능은 public으로 설정하여 사용자가 구현된 기능들은 자유롭게 접근하여 사용할 수 있도록 하였다.
변수는 private로 설정하여 보호하고 있기 때문에, public 섹션에 getter와 setter함수를 정의해서 사용자가 변수를 초기화 하고 데이터를 복사해 가져올 수 있도록 하였다.
생성자
- 객체가 생성될 때, 한 번 호출되는 함수이다.
- 보통 멤버 변수의 초기화를 하거나 객체가 동잘할 준비를 하기 위해 사용된다.
- 생성자는 반환 값이 없고, Class의 이름과 같은 함수 형태이다.
class Person
{
public:
Person(string DefaultName = "김아무개", int DefaultAge = 0)
{
Name = DefaultName;
Age = DefaultAge;
}
void SetName(string Name)
{
this->Name = Name;
}
void SetAge(int Age)
{
this->Age = Age;
}
string GetName() { return Name; }
int GetAge() { return Age; }
void DisPlay();
private:
string Name;
int Age;
};
void Person::DisPlay()
{
cout << "이름: " << Name << endl << "나이: " << Age << endl;
cout << endl;
}
int main()
{
Person A("김동현", 29);
Person B;
A.DisPlay();
B.DisPlay();
return 0;
}
위와 같이 생성자에 기본 매개변수를 넣을 수 있다.
Person A의 경우 생성자의 매개변수에 값을 넣어주어서 해당 값이 들어가 있는 것을 확인할 수 있고,
Person B의 경우 매개변수에 값을 넣어주지 않았기 때문에 기본 매개변수의 값이 들어있는 것을 확인할 수 있다.
#include <iostream>
using namespace std;
class Student
{
public:
// 동작 함수 정의
Student(int Kor = 0, int Math = 0, int Eng = 0)
{
this->Kor = Kor;
this->Math = Math;
this->Eng = Eng;
}
double GetAverage();
int GetMaxScore();
void SetKorScore(int Kor)
{
this->Kor = Kor;
}
void SetMathScore(int Math)
{
this->Math = Math;
}
void SetEngScore(int Eng)
{
this->Eng = Eng;
}
int GetKorScore() { return Kor; }
int GetMathScore() { return Math; }
int GetEngScore() { return Eng; }
private:
// 멤버 변수 정의
int Kor;
int Math;
int Eng;
};
double Student::GetAverage()
{
return Kor + Math + Eng / 3.0f;
}
int Student::GetMaxScore()
{
return max({ Kor,Math,Eng });
}
int main()
{
Student A(50, 60, 100);
cout << "제일 높은 점수: " << A.GetMaxScore() << endl << "전체 평균 점수: " << A.GetAverage();
return 0;
}
앞서 정의한 Student Class에 생성자를 적용해, 객체가 생성될 때 값을 전달해 더 깔끔하고 빠르게 동작할 수 있다.
코드파일 나누기
내부 구현은 사용자가 알 필요가 없기 때문에 Student Class를 정의, 구현, 사용자 실행으로 코드를 나누었다.
추가적으로 헤더파일에 정의할 때, #ifndef 는 '만약 헤더가 정의되어 있지 않다면 아래 코드를 수행하라' 의 의미이고, #define 은 '해당 헤더를 아래 코드와 같이 정의하라'는 의미이며 #ifdef일 경우에 단 한번만 수행한다. 그리고 정의가 끝나고 맨 마지막에 #endif 는 '#ifndef가 끝났다는 것을 알려준다'는 의미
'내배캠 > C++' 카테고리의 다른 글
Quick Sort 정렬 알고리즘 (0) | 2024.12.23 |
---|---|
유클리드 알고리즘 (1) | 2024.12.23 |
set 과 unordered_set (0) | 2024.12.22 |
Key-Value 자료구조 (0) | 2024.12.21 |
Binary_Search (0) | 2024.12.16 |