|
| 1 | +--- |
| 2 | +title: 클래스 |
| 3 | +description: C++ 클래스에 대한 내용 정리 |
| 4 | +author: gemini |
| 5 | +date: 2025-06-10 17:00:00 +09:00 |
| 6 | +categories: [C++] |
| 7 | +tags: [class] |
| 8 | +math: true |
| 9 | +mermaid: true |
| 10 | +--- |
| 11 | + |
| 12 | +# Class |
| 13 | + |
| 14 | +- class 멤버함수 구현(클래스 내부) |
| 15 | + |
| 16 | +``` |
| 17 | +#include <iostream> |
| 18 | + #include <algorithm> //max 함수 사용 |
| 19 | + #include <string> |
| 20 | + using namespace std; |
| 21 | + class Student |
| 22 | + { |
| 23 | + //동작 정의(이를 멤버함수라고 합니다) |
| 24 | + double getAvg() |
| 25 | + { |
| 26 | + return (kor + eng + math ) / 3.0; |
| 27 | + } |
| 28 | + int getMax() |
| 29 | + { |
| 30 | + return max(max(kor, eng), math); |
| 31 | + } |
| 32 | + |
| 33 | + //데이터 정의(이를 멤버변수라고 합니다.) |
| 34 | + int kor; |
| 35 | + int eng; |
| 36 | + int math; |
| 37 | + }; |
| 38 | +``` |
| 39 | + |
| 40 | +- class 멤버함수 구현(클래스 외부) |
| 41 | + |
| 42 | +``` |
| 43 | +#include <iostream> |
| 44 | + #include <algorithm> //max 함수 사용 |
| 45 | + #include <string> |
| 46 | + using namespace std; |
| 47 | + class Student |
| 48 | + { |
| 49 | + //동작 정의(이를 멤버함수라고 합니다) |
| 50 | + double getAvg(); |
| 51 | + int getMaxNum(); |
| 52 | + //데이터 정의(이를 멤버변수라고 합니다.) |
| 53 | + int kor; |
| 54 | + int eng; |
| 55 | + int math; |
| 56 | + }; |
| 57 | + |
| 58 | + double Student::getAvg() |
| 59 | + { |
| 60 | + return (kor + eng + math) / 3.0; |
| 61 | + } |
| 62 | + int Student::getMaxNum() |
| 63 | + { |
| 64 | + return max(max(kor, eng), math); |
| 65 | + // 다른 방법 return max({ kor, eng, math }); |
| 66 | + } |
| 67 | +``` |
| 68 | + |
| 69 | +- 접근제어 |
| 70 | + - 클래스의 멤버 함수나 변수에 접근할 때에, 객체 뒤에 멤버 접근 연산자 `.`을 사용한다 |
| 71 | + - **public** |
| 72 | + - 외부에서 직접 접근 가능 |
| 73 | + - 일반적으로 멤버 함수는 public |
| 74 | + - **private** (default) |
| 75 | + - 외부에서 직접 접근할 경우 컴파일 에러가 발생 |
| 76 | + - 일반적으로 멤버 변수는 private |
| 77 | + |
| 78 | +- getter와 setter |
| 79 | + - private에 있는 변수를 제어하기 위해 사용 |
| 80 | + - 가져올 때 getter |
| 81 | + - 바꿀 때 setter |
| 82 | + - 어디서 값 변경을 했는지 명시적이다 |
| 83 | + |
| 84 | +``` |
| 85 | +#include <iostream> |
| 86 | +#include <algorithm> //max 함수 사용 |
| 87 | +#include <string> |
| 88 | +
|
| 89 | +using namespace std; |
| 90 | +
|
| 91 | +class Student |
| 92 | +{ |
| 93 | +public: |
| 94 | + //동작 정의(이를 멤버함수라고 합니다) |
| 95 | + double getAvg(); |
| 96 | + int getMaxScore(); |
| 97 | +
|
| 98 | + void setMathScore(int math) |
| 99 | + { |
| 100 | + this->math = math; |
| 101 | + } |
| 102 | + void setEngScore(int eng) |
| 103 | + { |
| 104 | + this->eng = eng; |
| 105 | + |
| 106 | + } |
| 107 | + void setKorScore(int kor) |
| 108 | + { |
| 109 | + this->kor = kor; |
| 110 | + } |
| 111 | +
|
| 112 | + int getMathScore() { return math; } |
| 113 | + int getEngScore() { return eng; } |
| 114 | + int getKorScore() { return kor; } |
| 115 | +
|
| 116 | +private: |
| 117 | + //데이터 정의(이를 멤버변수라고 합니다.) |
| 118 | + int kor; |
| 119 | + int eng; |
| 120 | + int math; |
| 121 | +}; |
| 122 | +
|
| 123 | +double Student::getAvg() |
| 124 | +{ |
| 125 | + return (kor + eng + math) / 3.0; |
| 126 | +} |
| 127 | +
|
| 128 | +int Student::getMaxScore() |
| 129 | +{ |
| 130 | + return max(max(kor, eng), math); |
| 131 | +} |
| 132 | +
|
| 133 | +int main() |
| 134 | +{ |
| 135 | + Student s; |
| 136 | +
|
| 137 | + s.setEngScore(32); |
| 138 | + s.setKorScore(52); |
| 139 | + s.setMathScore(74); |
| 140 | +
|
| 141 | + //평균 최대점수 출력 |
| 142 | + cout << s.getAvg() << endl; |
| 143 | + cout << s.getMaxScore() << endl; |
| 144 | +
|
| 145 | + return 0; |
| 146 | +} |
| 147 | +``` |
| 148 | + |
| 149 | +- **생성자** |
| 150 | + - 객체를 생성할 때, 한 번 자동으로 호출되는 특별한 멤버 함수 |
| 151 | + - 필요한 멤버 변수를 초기화하거나 객체가 동작할 준비를 하기 위해 사용 |
| 152 | + - 반환형을 명시하지 않고, class 이름과 동일한 이름을 가진 함수 |
| 153 | + |
| 154 | +>정의된 class를 변수로 선언하면 해당 객체가 메모리에 올라간다<br> |
| 155 | +>이를 **인스턴스화**라고 한다 |
| 156 | +{. prompt-info} |
| 157 | + |
| 158 | +>객체가 생성될 때, 멤버 변수를 포함해서 필요한 정보들이 메모리에 올라간다<br> |
| 159 | +>이 작업이 완료되면 생성자가 호출된다 |
| 160 | +{. prompt-info} |
| 161 | + |
| 162 | +- 기본 생성자 잘못 사용한 케이스 |
| 163 | +1. 잘못된 매개변수 전달 |
| 164 | +``` |
| 165 | +#include <iostream> |
| 166 | + using namespace std; |
| 167 | + |
| 168 | + class Person { |
| 169 | + public: |
| 170 | + string name; |
| 171 | + int age; |
| 172 | + |
| 173 | + // 매개변수가 있는 생성자 |
| 174 | + Person(string n, int a) { |
| 175 | + name = n; |
| 176 | + age = a; |
| 177 | + } |
| 178 | + }; |
| 179 | + |
| 180 | + int main() { |
| 181 | + Person p("Tom"); // 에러: 생성자에 필요한 매개변수 부족 |
| 182 | + // 컴파일 에러: "no matching function for call to 'Person::Person(const char [4])'" |
| 183 | + // 매개변수 두 개를 요구하는 생성자에 하나의 매개변수만 전달하여 매칭되지 않음 |
| 184 | + p.display(); |
| 185 | + return 0; |
| 186 | + } |
| 187 | +``` |
| 188 | + |
| 189 | +2. 선언만 하지 정의하지 않음 |
| 190 | +``` |
| 191 | +#include <iostream> |
| 192 | + using namespace std; |
| 193 | + |
| 194 | + class Person { |
| 195 | + public: |
| 196 | + string name; |
| 197 | + int age; |
| 198 | + |
| 199 | + // 생성자를 선언만 하고 정의하지 않음 |
| 200 | + Person(string n, int a); |
| 201 | + }; |
| 202 | + |
| 203 | + int main() { |
| 204 | + Person p("Alice", 25); // 선언된 생성자의 정의가 없으므로 컴파일 에러 발생 |
| 205 | + cout << "Name: " << p.name << ", Age: " << p.age << endl; |
| 206 | + return 0; |
| 207 | + } |
| 208 | +``` |
| 209 | + |
| 210 | +3. 기본 생성자를 잘못 호출 |
| 211 | +``` |
| 212 | +#include <iostream> |
| 213 | + using namespace std; |
| 214 | + |
| 215 | + class Person { |
| 216 | + public: |
| 217 | + string name; |
| 218 | + int age; |
| 219 | + |
| 220 | + void temp() {} |
| 221 | + Person(string n, int a) {} |
| 222 | + }; |
| 223 | + |
| 224 | + int main() { |
| 225 | + Person p("a", 30); |
| 226 | + Person p2; |
| 227 | + |
| 228 | + p.temp(); |
| 229 | + p2.temp(); |
| 230 | + |
| 231 | + return 0; |
| 232 | + } |
| 233 | +``` |
| 234 | + |
| 235 | +- class를 구현할 때, 보통 클래스의 선언부(헤더)와 구현부(소스 파일)을 분리한다 |
| 236 | + |
| 237 | +>굳이 파일을 나눠서 구현하는 이유<br> |
| 238 | +>책을 예로 책의 전체 구성을 설명해 주는 목차 혹은 서론 없이 바로 본론으로 들어가게 되면, 전체적인 구조를 파악하기 어렵다<br> |
| 239 | +>헤더 파일에 class를 정의하는 것은 목차를 만든다 생각하면 되고, 소스 파일에 세부 구현하는 것은 실제 책 내용이라고 생각하면 된다<br> |
| 240 | +>이렇게 하면 유지 보수성과 가독성 면에서 유리해진다 |
| 241 | +{. prompt-tip} |
| 242 | + |
| 243 | + |
| 244 | + |
0 commit comments