[C++] 클래스(Class)(2) 인터페이스(Interface)로서의 클래스 - 1

Gamchan Kang·2023년 4월 10일
0

C++

목록 보기
8/11
post-thumbnail

C++에서 클래스를 사용하는 이유에는 객체 간 용이한 연결도 있다. 이번 포스팅에서는 객체 간 연결에 집중해서 클래스를 서술하려 한다.


1. 멤버 초기화 목록(member initializer list)

클래스를 디자인할때 멤버 변수로 다른 클래스 객체를 가지기도 한다.

class A {
	...
};

class B {
	private:
    	A a;
        int x;
    public:
		B(	){	}	// 어떤 방식으로 초기화?
};

그러면 위 코드와 같이 초기화할 때 정확성과 효율이 떨어진다. 어떤 값으로 private 변수가 초기화됐는지, 무엇을 참조하는지 모르기 때문이다. 따라서 멤버 초기화 목록을 생성자에 사용한다.

public:
	B(A a_, int x_):
    	a(a_) {x = x_;}	// 만약 내용이 없어도 중괄호를 넣어줘야 한다.

반복을 줄이는 코드가 좋은 디자인 패턴이라고 한다. initializer를 잘 활용하면 불필요한 반복을 줄일 수 있다.


2. 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는 다음 포스팅에서 설명할 예정이다.



3. 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 키워드는 객체 간 접근을 쉽게 만든다.

profile
Someday, the dream will come true

0개의 댓글