[C++/Syntax] Class 3

Const와 Friend와 Static

Class에선 private를 다른 class에서 사용하게하고 싶을 때 friend를 써서 사용이 가능하게할 수 있다.
또한 static, const 또한 class 자체에 혹은 class 변수, 함수등에 사용될 때 그 쓰임에 대해 알아보자.


Const

class Person {
private:
	char name[10];
	int pox, poy;
	friend class Trip;
public:
	Person(const char name[], int pox, int poy) {
		strcpy(this->name, name);
		this->pox = pox;
		this->poy = poy;
	}
	void ShowPostion() const {
		std::cout << pox << " " << poy << std::endl; 
		return;
	}
	void work() {
		pox++;
		poy++;
	}
};
int main(){
	const Person man("man",10,10);
	// man.work(); // 에러가난다
	man.ShowPosition();
	return 0;
}
  1. Class에 const를 설정해 줄 수 있는데, 선언은 const PERSON man("man",10,10);과 같은 형식으로 하고
    man.work() 함수처럼 Class 내부의 변수를 수정 하는 메소드를 부를시 에러가 발생한다.
  2. 또한 class 내부 함수에 const를 설정해 줄 수 있는데 void ShowPosition() const { .. }와 같은 방식으로 선언하며,
    이렇게 const선언된 함수에선 Class 변수를 수정 할 수 없다. (함수 내부에서 선언된 변수는 상관없다.)
  3. 마지막으로 const 선언된 함수와 그렇지 않은 함수에 대해서 오버라이트가 가능하다.
    호출되는 방식은 class가 const면 const함수를 불러오고 그렇지 않으면 일반함수를 불러온다.

 

Friend

Class의 private변수는 다른 class에서 접근을 하지 못하는데 friend를 통해 다른 Class에서 접근이 가능하게 할 수 있다.

class Person {
private:
	char name[10];
	int pox, poy;
	friend class Trip;
public:
	Person(const char name[], int pox, int poy) {
		strcpy(this->name, name);
		this->pox = pox;
		this->poy = poy;
	}

	void ShowPostion() const {
		std::cout << pox << " " << poy << std::endl; 
		return;
	}
	void work() {
		pox++;
		poy++;
	}
	~Person() {
		std::cout << "Call Desconstructor" << std::endl;
	}
};

class Trip {
private:
	Person man;
	Person woman;
	int number;
public:
	Trip(const char name1[], const char name2[], const int pox1, const int poy1, const int pox2, const int poy2)
		:man(name1, pox1, poy1), woman(name2, pox2, poy2), number(pox1)
	{
		// Code
	}
	void ShowTest() {
		std::cout << man.pox++ << std::endl;
	}
};

int main(){
	Trip trip("man", "woman", 10, 10, 10, 10);
	trip.ShowTest();
	return 0;
}

5 번째 줄을 보면 friend class Trip이렇게 선언되어 있는데,
Trip 클래스 안에 ShowTest() 를 보면 man.pox++ 로 private 변수를 직접 접근하는 것을 볼 수 있다.

이 friend선언한 class에서 자기 class의 private 변수를 모두 접근 할 수 있게된다.
또한 각각의 함수에 따라 선언도 가능한데,
friend Person Trip::ShowTest();이런식으로 함수 각각에 friend 선언을 해주는 용도 이외엔 잘 사용되지 않고 권고하지도 않는다.

 

Static

전역 변수를 설정해 주는 기능을 한다.

하지만 Class 안에서 static 선언이 되었을 땐, Class 안에서 자유로이 접근이 가능하고 Class가 사라질때 까지 유지된다.
또한 Person::pox++처럼 직접적으로 접근도 가능하다.

함수 또한 static으로 선언이 가능한데,
이는 외부에 함수를 설치 한 것 과 거의 동일하며 접근 방식만 Class.StaticFunc() 혹은 CLASS::StaticFunc()로 접근한다.

 

++ Mutable

mutalbe은 void func() const { .. } 처럼 const 선언된 함수에서도 변경이 가능하게 하기 위한 키워드 이다.

사용 빈도수도 낮으며, 권고도 하지 않는다고 ㅎ나다.

카테고리C++

글의 문제가 있다면 댓글을 달아 주세요.

이 사이트는 스팸을 줄이는 아키스밋을 사용합니다. 댓글이 어떻게 처리되는지 알아보십시오.