개념 | 설명 |
---|---|
getter | private 멤버변수를 읽는 함수 |
setter | private 멤버변수를 수정하는 함수 |
캡슐화 | 클래스 내부 데이터를 외부에서 직접 못 건드리게 보호 |
-
-
Save sudoswift/ce19fb9d902cd8f2fd81b3ae5c844ccd to your computer and use it in GitHub Desktop.
getter&setter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Person { | |
private: | |
string name; | |
int age; | |
public: | |
Person(string n, int a); | |
// Getter | |
string getName(); | |
int getAge(); | |
// Setter | |
void setName(string n); | |
void setAge(int a); | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "Person.h" | |
#include <iostream> | |
using namespace std; | |
Person::Person(string n, int a) { | |
name = n; | |
setAge(a); // 유효성 검사 포함 가능 | |
} | |
string Person::getName() { | |
return name; | |
} | |
int Person::getAge() { | |
return age; | |
} | |
void Person::setName(string n) { | |
name = n; | |
} | |
void Person::setAge(int a) { | |
if (a >= 0 && a <= 150) | |
age = a; | |
else { | |
cout << "⚠️ 유효하지 않은 나이입니다!\n"; | |
age = 0; | |
} | |
} | |
// | |
Person p("홍길동", 25); | |
cout << p.getName() << "의 나이: " << p.getAge() << endl; | |
p.setAge(-99); // ⚠️ 유효하지 않은 나이입니다! |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
리턴타입 get변수() { | |
return 변수; | |
} | |
void set변수(타입 값) { | |
if (검사) 변수 = 값; | |
} |
Comments are disabled for this gist.