4주차
상속
class Base {
std::string s;
public:
Base() : s("부모") { std::cout << "부모 클래스" << std::endl; }
void print_s() { std::cout << s << std::endl; }
};
class Derived : public Base { // : public 부모클래스명
std::string s;
public:
Derived() : Base(), s("자식") { //생성자
std::cout << "자식 클래스" << std::endl;
// Base 에서 print_s() 을 물려 받았으므로
// Derived 에서 당연히 호출 가능하다
print_s();
}
};
자식클래스는 자신의 함수 + 부모 함수까지 사용가능
- 자식 클래스에서 주의할 점
Derived() : Base(), s("자식") { }
이때 Base() 즉 부모 클래스를 먼저 호출해야 함
예제)
#include <iostream>
#include <string>
class Base {
std::string s;
public:
Base() : s("기반") { std::cout << "기반 클래스" << std::endl; }
void what() { std::cout << s << std::endl; }
};
class Derived : public Base {
std::string s;
public:
Derived() : Base(), s("파생") {
std::cout << "파생 클래스" << std::endl;
// Base 에서 what() 을 물려 받았으므로
// Derived 에서 당연히 호출 가능하다
what();
}
};
int main() {
std::cout << " === 기반 클래스 생성 ===" << std::endl;
Base p;
std::cout << " === 파생 클래스 생성 ===" << std::endl;
Derived c;
return 0;
}
결과)
protected : 접근 지정자
- private : 자기 자신만 접근 가능
- protected : 자기 자신, 자식들 접근 가능
- public : 모두가 접근 가능
'C++' 카테고리의 다른 글
[C++] 파일 입출력 (0) | 2024.03.15 |
---|---|
[C++] 한 줄 입력 받기, 공백 포함 입력 받기 | getline() (0) | 2023.08.09 |
[c++] 참조(레퍼런스), 포인터 개념 정리 (0) | 2023.03.31 |
[c++] 보안 취약 에러 | scanf, strcpy (0) | 2023.03.29 |
[C++] class 생성 (0) | 2023.03.29 |