C++에서 클래스를 사용하는 이유에는 객체 간 용이한 연결도 있다. 이번 포스팅에서는 객체 간 연결에 집중해서 클래스를 서술하려 한다.
클래스를 디자인할때 멤버 변수로 다른 클래스 객체를 가지기도 한다.
class A {
...
};
class B {
private:
A a;
int x;
public:
B( ){ } // 어떤 방식으로 초기화?
};
그러면 위 코드와 같이 초기화할 때 정확성과 효율이 떨어진다. 어떤 값으로 private
변수가 초기화됐는지, 무엇을 참조하는지 모르기 때문이다. 따라서 멤버 초기화 목록을 생성자에 사용한다.
public:
B(A a_, int x_):
a(a_) {x = x_;} // 만약 내용이 없어도 중괄호를 넣어줘야 한다.
반복을 줄이는 코드가 좋은 디자인 패턴이라고 한다. initializer를 잘 활용하면 불필요한 반복을 줄일 수 있다.
this
this
는 객체 자기 자신을 가리키는 포인터이다. 클래스 내부에서 멤버를 호출하거나, 자기 자신을 return
하는데 사용한다. 위 예시를 this
로 들어보면 다음과 같다.
class A {
...
};
class B {
private:
A a;
int x;
public:
B(A a, int x): a(a) {
this->x = x;
}
};
참고
this
는 initializer로 사용할 수 없다. non-static member이기 때문이다. static member는 다음 포스팅에서 설명할 예정이다.
friend
friend
는 외부 클래스에서 private
멤버로 접근하도록 지정하는 키워드이다. ID, Password로 예시를 들어보면 다음과 같다.
#include <iostream>
class Password {
private:
std::string passwordContent;
public:
Password(std::string password): passwordContent(password) {}
friend class ID;
};
class ID {
private:
Password password;
std::string id;
public:
ID(std::string id, Password pw): id(id), password(pw) {}
bool isMatch(Password pw){
if(pw.passwordContent == this->password.passwordContent) {
return true;
}
return false;
}
};
int main() {
Password p1("Hello");
ID id("World", p1);
Password p2("HELLO");
if(!id.isMatch(p1)){
std::cout << "Password 1 doesn't match" << std::endl;
} else {
std::cout << "Password 1 match" << std::endl;
}
if(!id.isMatch(p2)){
std::cout << "Password 2 doesn't match" << std::endl;
} else {
std::cout << "Password 2 match" << std::endl;
}
return 0;
}
class Password {
private:
std::string passwordContent;
...
friend class ID;
};
class ID {
bool isMatch(Password pw){
if(pw.passwordContent ...
};
이런 friend
키워드는 객체 간 접근을 쉽게 만든다.