chap4. 클래스의 완성
1. 정보은닉(Information Hiding)
멤버변수를 private로 선언하고, 해당 변수에 접근하는 함수를 별도로 정의하여, 안전한 형태의 접근을 유도하는 것.
int GetX() const;
void ShowInfo() const;
- const 함수 : “이 함수 내에서 멤버변수의 값을 변경하지 않겠다” 의미
- const 함수 내에서 const 가 아닌 함수를 호출할 수 없음.
- const 참조자를 가지고 const 가 아닌 함수를 호출할 수 없음.
2. 캡슐화(Encapsulation)
관련 있는 함수와 변수를 하나의 클래스 안에 묶는 것.
3. 생성자(Constructor)
생성자 : Class 이름과 함수의 이름 동일, 반환형x, 오버로딩 가능.
매개변수의 defalut 값 설정 가능.(이 경우 유의)
객체 생성시 딱 한번 호출. 초기화에 사용.
SimpleClass c1(); // no
SimpleClass c1; // ok – no-argument constructor 호출
SimpleClass * c1 = new SimpleClass(); // ok
- no-argument constructor 호출시, 동적 할당의 형태로만 호출할 것.
SimpleClass c1(20,40);
SimpleClass * c1 = new SimpleClass(20,40);
SimpleClass c2;
SimpleClass * c2 = new SimpleClass();
-같은 데이터를 가진 객체가 만들어지나, 일반적인 생성과, 동적메모리 할당의 차이가 있다는 것에 유념할 것.
4. 멤버 이니셜라이저(Member Initializer)
멤버변수로 객체를 가질 때 Member Initializer를 사용해 초기화한다.
Class Point{
private:
int x;
int y;
public:
Point(const int &xp, const int &yp);
}
Point::Point(const int &xp, const int &yp){
x = xp;
y = yp;
y = yp;
};
Class Rectengle{
private:
Point left;
Point right;
public:
Rectengle(const int &x1, const int &y1, const int &x2, const int &y2);
};
Rectengle::Rectengle(
const int &x1, const int &y1, const int &x2, const int &y2) :left(x1,y1), right(x2,y2){ . . . . . . . }
const int &x1, const int &y1, const int &x2, const int &y2) :left(x1,y1), right(x2,y2){ . . . . . . . }
- 클래스 내 선언은 그냥 해주고, 정의시에 “: + 객체의 constructor”
(물론, 밖에 안빼도 ok, 길면 빼고 아니면 같이 써버려~)
- ‘:left(x1,y1)’ : 객체 left 생성할 때 x1,y1을 인자로 받는 생성자 호출
- ‘right(x2,y2)’ : 객체 right 생성할 때 x2,y2을 인자로 받는 생성자 호출
+] 객체의 생성순서
1. 메모리할당.
2. Member Initializer로 멤버객체 초기화.
3. 생성자의 몸체 실행.
class FruitSeller{
private:
const int APPLE;
int numOfApple;
int &myMoney;
public:
FruitSeller(int price, int num, int &money)
: APPLE(price), numOfApple(num), myMoney(money)
{ . . . }
};
- Member Initializer로 변수 및 const 및 참조자도 초기화 가능
- “: 변수이름(argument)” 의 형태로 초기화 가능.
- 이 방식이 더 빠르고, 더 명확한 방법임.(변수 선언과 동시에 초기화)
+] malloc 사용시 공간 할당 후 생성자 호출하지 않음.
new 사용시 공간 할당 후, 생성자 자동 호출 (정의되지 않아도 defalut constructor 생성 후 호출 – 아무일도 하지 않음)
- defalut constructor는 어떠한 생성자도 정의되어 있지 않을때만 자동 생성됨.
- argument 받는 constructor만 있는데, no-argument로 생성시 에러.
- 특정 constructor를 private으로 선언시, 객체 생성방법 제한 가능.
5. 소멸자(Destructor)
class Person{
private:
char * name;
int age;
public:
Person(char * myname, int myage){
int len = strlen(myname)+1; //종료문자포함위해 +1
name = new char[len]; //메모리절약 동적할당
strcpy(name, myname);
age = myage;
}
~Person(){
delete []name;
}
};
- Destructor : “~”+“클래스 이름”+“()”의 형태로 정의. 반환형 없음.
- 객체 소멸과정에서 자동으로 호출되며, 따로 정의하지 않으면 defalut 소멸자가 자동 생성됨.
- Class 내에서 동적할당한 공간이 있다면 반드시 delete통해 해제할 것.
6. 객체 배열
SoSimple * p1 = new SoSimple[10];
- SoSimple Class의 객체 10개 생성.
- 배열로 생성시, no-argument constructor가 자동 호출됨.
- (다른 인자전달 constructor 사용 불가!)
- 이후 for문 이용해, 일일이 초기화 해야함.(constructor 사용 불가!)
7. 객체 포인터 배열 을 쓰면 되지~
Person * parr[3];
char name[100];
int num;
for(int i = 0; I < 3 ; i++){
cin>>name; cin>>num;
parr[i] = new Person(name,num);
}
delete parr[0];
delete parr[1];
delete parr[2];
- new 써서 동적메모리 할당 했으니, delete 해줘야 함.
8. this 포인터
this 포인터는 해당 객체의 주소를 가리키는 포인터임.
Circle donut;
Circle * p;
p = &donut;
double d = p -> getarea();
- 객체 이름으로 멤버에 접근할 때는 . 연산자를 이용하지만, 객체 포인터로 멤버에 접근할 때는 -> 연산자를 사용한다.
class TwoNumber{
private:
int num1;
int num2;
public:
TwoNumber(int num1,num2){
this->num1 = num1; //해당 객체의 멤버변수 접근
this->num2 = num2;
}
}
- 같은 이름을 가진 변수구분에 아주 유용하다.
9. self-reference 반환
Class SelfRef{
private:
private:
int num;
public:
SelfRef(int n) : num(n){...}
SelfRef& Adder(int n){ //class의 참조값 리턴.
num += n; 참조값으로 받으면, 직접접근 가능.
return *this;
}
}
SelfRef obj(3);
SelfRef &ref = obj.Adder(5); //참조값 리턴이니 참조값으로 받음.
ref.Adder(7).Adder(3);
- 객체 포인터(->)가 아닌 참조값(.)으로 직접 접근이 가능함.
댓글 없음:
댓글 쓰기