우리는 클래스를 기반으로도 포인터 변수를 선언할 수 있다. 예를 들어서 Person이라는 이름의 클래스가 정의되었다면, Person 객체의 주소 값 저장을 위해서 다음과 같이 포인터를 변수를 선언할 수 있다.
Person *ptr; //포인터 변수 선언
ptr = new Person(); //포인터 변수의 객체 참조
위의 두 문장이 실행되면, 포인터 Ptr은 Person 객체를 가리키게 된다. 그런데 Person형 포인터는 Person 객체뿐만 아니라, Person을 상속하는 유도 클래스의 객체도 가리킬 수 있다.
class Student : public Person{
...
};
class PartTimeStudent : public Student{
...
};
Person *ptr = new Student();
//유도 클래스인 Student객체를 Person형 포인터 변수가 가리키고있다.
Person *ptr = new PartTimeStudent();
//Person형 포인터 변수가 PartTimeStudent 객체도 가리킬 수 있다.
Student * ptr = new PartTimeStudent();
//Student형 포인터 변수도 PartTimeStudent 객체를 가리킬 수 있다.
C++에서, AAA형 포인터 변수는 AAA 객체 또는 AAA를 직접 혹은 간접적으로 상속하는 모든 객체를 가리킬 수 있다.(객체의 주소 값을 저장할 수 있다.
학생(Student)은 사람(Person)이다.
근로학생(PartTimeStudent)은 학생(Student)이다.
근로학생(ParTimeStudent)은 사람(Person)이다
함수의 오버라이딩(함수의 오버로딩과 혼동하지 말자)
.
.
.
class PermanentWorker : public Employee{
.
.
public:
int GetPay() const{}
int ShowSalaryInfo() const{}
};
class SaleWorker : public PermanentWorker{
private:
.
.
public:
int Getpay() cont{
return PermanetWorker::GetPay() + (int)(SalesResult*bonusRatio);
//PermanentWorker의 GetPay 함수 호출
.
.
}
'c++' 카테고리의 다른 글
[C++] 템플릿(Template)에 대한 이해와 함수 템플릿 (0) | 2023.06.09 |
---|---|
[C++]가상함수(Virtual Function), 다형성(Polymorphism) (0) | 2023.06.09 |
[C++]상속(Inheritance)의 이해 (0) | 2023.05.14 |
[C++]복사 생성자(Copy Constructor) (0) | 2023.05.05 |
[C++]연산자 오버로딩의 이해와 유형 (0) | 2023.04.30 |