클래스

이현진·2023년 4월 14일
0

C++

목록 보기
12/13
post-thumbnail

선언

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] 등의 객체를 생성하려 하면 컴파일 에러가 발생한다. 왜일까? 바로 빈값으로 객체를 생성하려 했기 때문이다. 지금의 생성자는 heightweight를 모두 요구하는 형태로, 인자가 없이는 생성 불가능하다. 이는 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;
}

방법1. 초기화

생성자에 객체 생성시 자동으로 초기화될 임의의 값을 넣어주는 것이다. 하지만 임의의 값이 들어가선 안되는 경우도 더러 있을 것이다.

class Student {
    int height, weight;

    Student(int height = 0, int weight = 0) {
        this->height = height;
        this->weight = weight;
        }
};

방법2. 생성자 추가

빈 값으로도 객체를 생성 가능한 생성자를 추가해주는 방법이다. 같은 함수명을 가진 생성자도 추가할 수 있다.

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;
}
profile
세상의 모든 지식을 담을 때까지

0개의 댓글