반응형
안녕하세요. 훈츠입니다. 금일은 클래스의 서브타입과 다중상속에 대해 포스팅 합니다.
서브 타입의 원리
클래스를 포인터로 선언후, 하위 클래스에서 상위 클래스로 접근이 가능 하다. (암시적 형변환)
- 하위 클래스에서 상위 클래스로 암시적 형변환이 된다.
- 상위 클래스에서 상위클래스로 접근은 불가 하다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
//훈스 블로그---------------------------------------------------------------------------------------------------코드//
class A
{
public:
void Print() { cout << "A클래스" << endl;}
};
class B : public A
{
public:
void Print() { cout << "B클래스" << endl; }
};
class C : public B
{
public:
void Print() { cout << "C클래스" << endl; }
};
int main()
{
A* ap; // a 포인터
B* bp; // b 포인터
C* cp; // c 포인터
C c;
B b;
A a;
ap = &b; // b 를 a 클래스로 변환
ap->Print(); // 프린트 출력 : "A클래스"
bp = &c; // c 를 b 클래스로 변환
bp->Print();// 프린트 출력 : "B클래스"
cp = &a; // 타입 캐스팅 불가!!!!
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs |
다중 상속 ( Multiple inheritance)
두 클래스의 특성을 함께 사용 가능
- 다중 상속을 통해 여러 클래스의 기능을 사용할수 있습니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
//훈스 블로그---------------------------------------------------------------------------------------------------코드//
class A
{
public:
void PrintA() { cout << "A클래스" << endl;}
};
class B
{
private : string m_str;
public :
void Get();
void PrintB() { cout << m_str << endl; }
};
void B::Get(){
cin >> m_str;
}
class C : public A, public B {
};
int main()
{
C Test; //C 클래스에 아무 펑션 없음.
Test.Get(); //상속받은 B 의 함수인 GET을 호출하여 값을 받아옴
Test.PrintA(); //상속받은 A 의 PrintA() 함수 호출
Test.PrintB(); //상속받은 B 의 PrintB() 함수 호출
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
http://colorscripter.com/info#e" target="_blank" style="text-decoration:none;color:white">cs |
'컴퓨터 언어 > C++' 카테고리의 다른 글
[C++] C++ 14일차 가상함수와 추상클래스 (0) | 2020.04.16 |
---|---|
[C++] C++ 13일차 가상함수와 다형성 (0) | 2020.04.15 |
[C++] C++ 11일차 상속 3 (0) | 2020.04.13 |
[C++] C++ 10일차 상속 2 (0) | 2020.04.10 |
[C++] C++ 9일차 상속 1 (0) | 2020.04.09 |