c++에서의 클래스는 다음과 같이 선언할 수 있다.
class Student {
int height, weight;
Student(int height, int weight) {
this->height = height;
this->weight = weight;
}
};
기본적으로 클래스의 모든 멤버는 private
이며, 클래스 외부에서 접근할 수 없다. 따라서, 외부에서 접근하고자 하는 멤버는 public
에 지정해줘야한다. 이 때 public
을 접근지정자라 한다.
#include <iostream>
using namespace std;
class Student {
public:
int height, weight;
Student(int height, int weight) {
this->height = height;
this->weight = weight;
}
};
int main() {
Student chulsu = Student(180, 70);
cout << chulsu.height;
return 0;
}
private (default)
public
protected
우리는 class
내에 같은 이름을 가진 함수를 하나 발견할 수 있다. 이는 객체 생성시에 함수처럼 인자를 받아와 객체의 값으로 넣어주는 역할을 하며, 생성자라 부른다.
동일한 클래스 선언으로 Student students[5]
등의 객체를 생성하려 하면 컴파일 에러가 발생한다. 왜일까? 바로 빈값으로 객체를 생성하려 했기 때문이다. 지금의 생성자는 height
와 weight
를 모두 요구하는 형태로, 인자가 없이는 생성 불가능하다. 이는 2가지 해결방법이 있다.
#include <iostream>
using namespace std;
class Student {
int height, weight;
Student(int height, int weight) {
this->height = height;
this->weight = weight;
}
};
int main() {
Student students[5];
return 0;
}
생성자에 객체 생성시 자동으로 초기화될 임의의 값을 넣어주는 것이다. 하지만 임의의 값이 들어가선 안되는 경우도 더러 있을 것이다.
class Student {
int height, weight;
Student(int height = 0, int weight = 0) {
this->height = height;
this->weight = weight;
}
};
빈 값으로도 객체를 생성 가능한 생성자를 추가해주는 방법이다. 같은 함수명을 가진 생성자도 추가할 수 있다.
class Student {
int height, weight;
Student(int height, int weight) {
this->height = height;
this->weight = weight;
}
Student() {}
};
c++에서 클래스의 멤버변수를 기준으로 정렬하기 위해서는 custom comparator
가 필요하다. custom comparator
는 정렬할 원소 두개를 비교할 때 사용하는 기준이다.
#include <iostream>
#include <algorithm>
using namespace std;
class Patient {
public:
int height, weight;
Patient(int height, int weight) {
this->height = height;
this->weight = weight;
}
};
// height를 기준으로 오름차순 정렬하는 custom comparator
bool cmp(Patient a, Patient b) {
if (a.height < b.height)
return true;
else
return false;
}
int main() {
Patient patients[4] = {
Patient(180, 70),
Patient(158, 50),
Patient(165, 58),
Patient(172, 68)
};
// 정렬
sort(patients, patients + 4, cmp);
for (int i = 0; i < 4; i++) {
cout << patients[i].height << " " << patients[i].weight << endl;
}
return 0;
}
만약 height
가 동일한 값일 때는, weight
로 정렬하고 싶다면 어떻게 하면 될까? custom comparator
를 구체화시키면 된다. height
가 동일한 경우의 처리 방법을 이어서 작성해 주면 된다.
bool cmp(Patient a, Patient b) {
if (a.height != b.height)
return a.height < b.height;
return a.weight < b.weight;
}