소프트웨어/C/C++

c/c++] 객체포인터와 객체레퍼런스

cs만두 2013. 8. 11. 16:43

#include<iostream>


using std::cin;

using std::cout;

using std::endl;


class Person{

private:

int age;

public:

Person(int _age=0){

age=_age;

cout<<_age<<"살의 인간이 생성되었습니다"<<endl;

}

void Breath();

};

void Person::Breath(){ cout<<"숨을쉽니다"<<endl; }


class Student : public Person{

public:

Student(int _age=0) : Person(_age){

cout<<"학생이 생성되었습니다"<<endl;

}

void StudyHard();

};

void Student::StudyHard(){ cout<<"열심히 공부를 합니다"<<endl; }



class EleteStudent : public Student{

public:

EleteStudent(){

cout<<"엘리트가 되었습니다"<<endl;

}

void GoSeoulUniv();

};

void EleteStudent::GoSeoulUniv(){ cout<<"서울대에 갔습니다"<<endl; }



int main(void){

//////////객체포인터//////////////

Person* p[3];

p[0]= new Person();

p[1]= new Student(20);

p[2]= new EleteStudent();

p[0]->Breath();//객체포인터Person*로 Person을 상속받은 하위자식들을 생성할경우

p[1]->Breath();//매서드 접근권한이 딱 Person이 갖는 Breath까지만 주어진다.

p[2]->Breath();//이것을 해결하기위해 객체 reference를 사용한다.


//////////객체참조(Object Reference)//////////////////////

EleteStudent e; //상속의상속의 결과물

Student& refStudent= e;//엘리트의 학생레퍼런스를 생성

       Person& refPerson= e;//엘리트의 사람레퍼런스를 생성

e.GoSeoulUniv(); //원래 다상속받은 객체라서 다 접근 가능 

refStudent.StudyHard(); //base의 breath 매서드와 자기자신의 studyHard까지 접근 가능

refPerson.Breath();// base가 없으므로 자기자신의 breath 메서드까지 접근 가능 



return 0;

}


객체포인터를 이용해서 base로 하위 상속클래스 객체를 생성할경우 접근권한이 base에서 선언한 것까지만 허용된다.
(control을 쉽게하기위해 base로 리스트나 어레이를 관리하는데 이럴경우 접근권한 해결을 해줘야함)
그래서 접근권한을 해결하기위해 객체레퍼런스를 선언한다.
&를 이용해 객체의 다른 이름들을 만들고 접근하면 해결