영넌 개발로그
[객체 기반 프로그래밍] getter, setter / object as 파라미터, 반환 값 본문
getter, setter
private member variable은 class 내에서만 정의가 가능함. 즉, object를 생성했을 때 이 변수를 read나 write할 수 없다는 뜻과 같아진다. 그러나 read나 write할 수 있는 member function을 public으로 필요로 함
객체 기반 프로그래밍의 범용적인 단어로 쓰이고 있다.
- read하는 function을 getter
- write하는 function을 setter
- 이름을 붙일 때에는 get/set + variable_name
- 보통 class 내부에서 선언 (inline이 됨->실행속도 빨라짐)
ex) 멤버 변수 age가 있을 때 getAge(), setAge() 와 같은 함수를 public으로 만들어줌
#include <iostream>
#include <string>
using namespace std;
class Person
{
private:
int age;
public:
int getAge() {
return age;
}
void setAge(int _age) {
age = _age;
} //앞에 '_'면 local 변수라고 인식
};
int main() {
Person p;
p.setAge(50);
return 0;
}
object as function parameter
객체를 함수의 파라미터로 사용하기
call-by-value와 같다고 생각하면 편하다! 새로 공간을 만들고 복사해온다. 함수가 끝나면 사라짐
p_of_foo는 p를 복사한다. p_of_foo를 수정해도, p는 바뀌지 않는다.
#include <iostream>
using namespace std;
class Person
{
public:
int age;
};
void foo(Person p_of_foo) {
p_of_foo.age = p_of_foo.age * 2;
}
int main() {
Person p;
p.age = 20;
foo(p);
cout << "Age: " << p.age << endl;
return 0;
}
object reference as function parameter
call_by_value로 하면 메모리와 속도가 느려진다. 이를 줄이기 위해 reference를 사용하자!
#include <iostream>
using namespace std;
class Person
{
public:
int age;
};
void foo(Person& p_of_foo) {
p_of_foo.age = p_of_foo.age * 2;
}
int main() {
Person p;
p.age = 20;
cout << "Before Age: " << p.age << endl;
foo(p);
cout << "After Age: " << p.age << endl;
return 0;
}
object as function return value
object&를 반환하는 건 사실상 사용할 수 없는 코드임.. 함수가 끝나면 오리지날 공간이 사라지므로
아래 처럼 두가지 방법이 존재
복사본이 복사됨 #include <iostream> using namespace std; class Person { public: int age; Person() : age(0) {}; }; Person bar() { Person _p; return _p; } int main() { Person p = bar(); cout << "Age: " << p.age << endl; return 0; } |
주소를 복사함 #include <iostream> using namespace std; class Person { public: int age; Person() : age(0) {}; }; Person* bar() { Person* _p = new Person(); return _p; } int main() { Person* p = bar(); cout << "Age: " << p.age << endl; return 0; } |
'코딩 > C++' 카테고리의 다른 글
[C++ 기초] STL : Standard template library / class array (0) | 2020.10.27 |
---|---|
[C++ 기초] Vector (0) | 2020.10.27 |
[C++ 기초] class overloading / 헤더파일 만들어 쓰기 / access control (public, private) (0) | 2020.10.27 |
[C++ 기초] 객체의 이해, 원 그리기 (0) | 2020.10.26 |
Comments