Skip to content

Instantly share code, notes, and snippets.

@sudoswift
Last active June 25, 2025 09:30
Show Gist options
  • Save sudoswift/ce19fb9d902cd8f2fd81b3ae5c844ccd to your computer and use it in GitHub Desktop.
Save sudoswift/ce19fb9d902cd8f2fd81b3ae5c844ccd to your computer and use it in GitHub Desktop.
getter&setter
개념 설명
getter private 멤버변수를 읽는 함수
setter private 멤버변수를 수정하는 함수
캡슐화 클래스 내부 데이터를 외부에서 직접 못 건드리게 보호
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);
};
#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); // ⚠️ 유효하지 않은 나이입니다!
리턴타입 get변수() {
return 변수;
}
void set변수(타입 값) {
if (검사) 변수 = 값;
}

Comments are disabled for this gist.