의 능력 수업 다른 클래스에서 속성과 특성을 파생시키는 것을 호출합니다. 계승 . 상속은 객체지향 프로그래밍의 가장 중요한 기능 중 하나입니다.
상속은 기존 클래스에서 새 클래스를 만드는 기능 또는 프로세스입니다. 생성된 새 클래스를 파생 클래스 또는 하위 클래스라고 하며 기존 클래스를 기본 클래스 또는 상위 클래스라고 합니다. 이제 파생 클래스는 기본 클래스에서 상속된다고 합니다.
파생 클래스가 기본 클래스를 상속한다는 것은 파생 클래스가 기본 클래스의 속성을 변경하지 않고 기본 클래스의 모든 속성을 상속하고 자체 클래스에 새로운 기능을 추가할 수 있음을 의미합니다. 파생 클래스의 이러한 새로운 기능은 기본 클래스에 영향을 미치지 않습니다. 파생 클래스는 기본 클래스에 대한 특수 클래스입니다.
- 하위 클래스: 다른 클래스로부터 속성을 상속받는 클래스를 서브클래스(Subclass) 또는 파생 클래스(Derived Class)라고 합니다.
- 슈퍼 클래스: 하위 클래스에 의해 속성이 상속되는 클래스를 기본 클래스 또는 슈퍼클래스라고 합니다.
이 기사는 다음과 같은 하위 주제로 구성되어 있습니다.
- 상속을 사용하는 이유와 시기는 무엇입니까?
- 상속 모드
- 상속 유형
상속을 사용하는 이유와 시기는 무엇입니까?
차량 그룹을 고려하십시오. 버스, 자동차, 트럭에 대한 클래스를 만들어야 합니다. FuelAmount(), capacity(), applyBrakes() 메서드는 세 클래스 모두에서 동일합니다. 상속을 피하면서 이러한 클래스를 생성하는 경우 아래 그림과 같이 세 클래스 각각에 이러한 함수를 모두 작성해야 합니다.

자바 날짜 현재
위 과정을 통해 동일한 코드가 3번 중복되는 것을 확인할 수 있습니다. 이로 인해 오류 및 데이터 중복 가능성이 높아집니다. 이러한 상황을 방지하기 위해 상속이 사용됩니다. Vehicle 클래스를 생성하고 그 안에 이 세 가지 함수를 작성하고 Vehicle 클래스에서 나머지 클래스를 상속하면 간단히 데이터 중복을 피하고 재사용성을 높일 수 있습니다. 세 가지 클래스가 Vehicle 클래스에서 상속되는 아래 다이어그램을 살펴보세요.

상속을 사용하면 기본 클래스(Vehicle)에서 나머지 세 클래스를 상속받았기 때문에 함수를 세 번 작성하는 대신 한 번만 작성하면 됩니다.
C++에서 상속 구현 : 기본 클래스에서 상속된 하위 클래스를 만들려면 아래 구문을 따라야 합니다.
파생 클래스: 파생 클래스는 기본 클래스에서 파생된 클래스로 정의됩니다.
통사론 :
class : { //body }>어디
class — 새 클래스를 생성하는 키워드
파생_클래스_이름 — 기본 클래스를 상속할 새 클래스의 이름
액세스 지정자 - 비공개, 공개 또는 보호 중 하나입니다. 둘 다 지정하지 않으면 PRIVATE가 기본값으로 사용됩니다.
base-class-name — 기본 클래스의 이름
메모 : 파생 클래스는 상속되지 않습니다. 입장 개인 데이터 멤버에게. 그러나 해당 클래스가 선언하는 전용 멤버를 포함하는 전체 상위 개체를 상속합니다.
예:
1. 클래스 ABC : 개인 XYZ //개인 파생
{ }
2. 클래스 ABC : 공개 XYZ //공개 파생
{ }
3. 클래스 ABC : 보호된 XYZ //보호된 파생
{ }
4. 클래스 ABC: XYZ //기본적으로 개인 파생
{ }
메모:
o 기본 클래스가 파생 클래스에 의해 비공개적으로 상속되는 경우 기본 클래스의 공용 멤버는 파생 클래스의 전용 멤버가 되므로 기본 클래스의 공용 멤버는 파생 클래스의 멤버 함수를 통해서만 액세스할 수 있습니다. 파생 클래스의 개체에는 액세스할 수 없습니다.
o 반면, 기본 클래스가 파생 클래스에 의해 공개적으로 상속되는 경우 기본 클래스의 공용 멤버도 파생 클래스의 공용 멤버가 됩니다. 따라서 기본 클래스의 공용 멤버는 파생 클래스의 개체뿐만 아니라 파생 클래스의 멤버 함수에서도 액세스할 수 있습니다.
// Example: define member function without argument within // the class #include using namespace std; class Person { int id; char name[100]; public: void set_p() { cout << 'Enter the Id:'; cin>> 아이디; 시합<< 'Enter the Name:'; cin>> 이름; } 무효 디스플레이_p() { cout<< endl <<'Id: '<< id << '
Name: ' << name <> 물론입니다; 시합<< 'Enter the Course Fee:'; cin>> 수수료; } 무효 디스플레이_s() { 디스플레이_p(); 시합<<'Course: '<< course << '
Fee: ' << fee << endl; } }; int main() { Student s; s.set_s(); s.display_s(); return 0; }> 산출:
자바 추상 클래스
Enter the Id: 101 Enter the Name: Dev Enter the Course Name: GCS Enter the Course Fee:70000 Id: 101 Name: Dev Course: GCS Fee: 70000>C++
// Example: define member function without argument outside the class #include using namespace std; class Person { int id; char name[100]; public: void set_p(); void display_p(); }; void Person::set_p() { cout<<'Enter the Id:'; cin>>아이디; 시합<<'Enter the Name:'; cin>>이름; } 무효 사람::display_p() { cout<> 물론; 시합<<'Enter the Course Fee:'; cin>>수수료; } void Student::display_s() { display_p(); 시합<<'
Course: '< 산출:
Enter the Id: 101 Enter the Name: Dev Enter the Course Name: GCS Enter the Course Fee: 70000 Id: 101 Name: Dev Course: GCS Fee: 70000>C++
// Example: define member function with argument outside the class #include #include using namespace std; class Person { int id; char name[100]; public: void set_p(int,char[]); void display_p(); }; void Person::set_p(int id,char n[]) { this->아이디=아이디; strcpy(이->이름,n); } 무효 사람::display_p() { cout< CPP
// C++ program to demonstrate implementation // of Inheritance #include using namespace std; // Base class class Parent { public: int id_p; }; // Sub class inheriting from Base Class(Parent) class Child : public Parent { public: int id_c; }; // main function int main() { Child obj1; // An object of class child has all data members // and member functions of class parent obj1.id_c = 7; obj1.id_p = 91; cout << 'Child id is: ' << obj1.id_c << '
'; cout << 'Parent id is: ' << obj1.id_p << '
'; return 0; }> 산출
Child id is: 7 Parent id is: 91>
위 프로그램에서 'Child' 클래스는 'Parent' 클래스로부터 공개적으로 상속되므로 'Parent' 클래스의 공개 데이터 멤버도 'Child' 클래스에 상속됩니다.
상속 모드: 상속에는 3가지 모드가 있습니다.
- 공개 모드 : 공개 기본 클래스에서 하위 클래스를 파생하는 경우. 그런 다음 기본 클래스의 공개 멤버는 파생 클래스에서 공개되고 기본 클래스의 보호 멤버는 파생 클래스에서 보호됩니다.
- 보호 모드 : Protected 기본 클래스에서 하위 클래스를 파생시키는 경우입니다. 그러면 기본 클래스의 공개 멤버와 보호 멤버가 모두 파생 클래스에서 보호됩니다.
- 프라이빗 모드 : Private 기본 클래스에서 하위 클래스를 파생하는 경우. 그러면 기본 클래스의 공개 멤버와 보호 멤버 모두 파생 클래스에서 비공개가 됩니다.
메모: 기본 클래스의 전용 멤버는 파생 클래스에서 직접 액세스할 수 없지만 보호된 멤버는 직접 액세스할 수 있습니다. 예를 들어 클래스 B, C, D에는 모두 아래 예에서 변수 x, y 및 z가 포함되어 있습니다. 그것은 단지 접근의 문제일 뿐입니다.
CPP // C++ Implementation to show that a derived class // doesn’t inherit access to private data members. // However, it does inherit a full parent object. class A { public: int x; protected: int y; private: int z; }; class B : public A { // x is public // y is protected // z is not accessible from B }; class C : protected A { // x is protected // y is protected // z is not accessible from C }; class D : private A // 'private' is default for classes { // x is private // y is private // z is not accessible from D };>
아래 표는 위의 세 가지 모드를 요약하고 공개, 보호 및 비공개 모드에서 파생될 때 하위 클래스에 있는 기본 클래스 멤버의 액세스 지정자를 보여줍니다.

상속 유형:-
- 단일 상속
- 다단계 상속
- 다중 상속
- 계층적 상속
- 하이브리드 상속
C++의 상속 유형
1. 단일 상속 : 단일 상속에서는 클래스가 하나의 클래스에서만 상속될 수 있습니다. 즉, 하나의 하위 클래스는 하나의 기본 클래스에서만 상속됩니다.

통사론 :
class subclass_name : access_mode base_class { // body of subclass }; OR class A { ... .. ... }; class B: public A { ... .. ... };>CPP // C++ program to explain // Single inheritance #include using namespace std; // base class class Vehicle { public: Vehicle() { cout << 'This is a Vehicle
'; } }; // sub class derived from a single base classes class Car : public Vehicle { }; // main function int main() { // Creating object of sub class will // invoke the constructor of base classes Car obj; return 0; }> 산출
This is a Vehicle>
C++
// Example: #include using namespace std; class A { protected: int a; public: void set_A() { cout<<'Enter the Value of A='; cin>>아; } 무효 disp_A() { cout< 출력:- A= 3의 값을 입력합니다. 3 B의 값을 입력합니다. = 5 5 3의 곱 * 5 = 15
C++
// Example: #include using namespace std; class A { protected: int a; public: void set_A(int x) { a=x; } void disp_A() { cout< 산출
Product of 4 * 5 = 20>
2. 다중 상속: 다중 상속은 클래스가 둘 이상의 클래스에서 상속할 수 있는 C++의 기능입니다. 즉 하나 아강 둘 이상의 것으로부터 상속됨 기본 클래스 .

통사론 :
class subclass_name : access_mode base_class1, access_mode base_class2, .... { // body of subclass }; class B { ... .. ... }; class C { ... .. ... }; class A: public B, public C { ... ... ... };>여기서 기본 클래스 수는 쉼표(', ')로 구분되며 모든 기본 클래스에 대한 액세스 모드를 지정해야 합니다.
CPP // C++ program to explain // multiple inheritance #include using namespace std; // first base class class Vehicle { public: Vehicle() { cout << 'This is a Vehicle
'; } }; // second base class class FourWheeler { public: FourWheeler() { cout << 'This is a 4 wheeler Vehicle
'; } }; // sub class derived from two base classes class Car : public Vehicle, public FourWheeler { }; // main function int main() { // Creating object of sub class will // invoke the constructor of base classes. Car obj; return 0; }> 산출
This is a Vehicle This is a 4 wheeler Vehicle>
C++
// Example: #include using namespace std; class A { protected: int a; public: void set_A() { cout<<'Enter the Value of A='; cin>>아; } 무효 disp_A() { cout<
자세한 내용은 기사를 참조하세요. 다중 상속 .
3. 다단계 상속 : 이 유형의 상속에서는 파생 클래스가 다른 파생 클래스에서 생성됩니다.

버블 정렬 자바
통사론:-
class C { ... .. ... }; class B:public C { ... .. ... }; class A: public B { ... ... ... };>CPP // C++ program to implement // Multilevel Inheritance #include using namespace std; // base class class Vehicle { public: Vehicle() { cout << 'This is a Vehicle
'; } }; // first sub_class derived from class vehicle class fourWheeler : public Vehicle { public: fourWheeler() { cout << 'Objects with 4 wheels are vehicles
'; } }; // sub class derived from the derived base class fourWheeler class Car : public fourWheeler { public: Car() { cout << 'Car has 4 Wheels
'; } }; // main function int main() { // Creating object of sub class will // invoke the constructor of base classes. Car obj; return 0; }> 산출
This is a Vehicle Objects with 4 wheels are vehicles Car has 4 Wheels>
4. 계층적 상속 : 이 유형의 상속에서는 단일 기본 클래스에서 둘 이상의 하위 클래스가 상속됩니다. 즉, 단일 기본 클래스에서 둘 이상의 파생 클래스가 생성됩니다.

통사론:-
class A { // body of the class A. } class B : public A { // body of class B. } class C : public A { // body of class C. } class D : public A { // body of class D. }>CPP // C++ program to implement // Hierarchical Inheritance #include using namespace std; // base class class Vehicle { public: Vehicle() { cout << 'This is a Vehicle
'; } }; // first sub class class Car : public Vehicle { }; // second sub class class Bus : public Vehicle { }; // main function int main() { // Creating object of sub class will // invoke the constructor of base class. Car obj1; Bus obj2; return 0; }> 산출
This is a Vehicle This is a Vehicle>
5. 하이브리드(가상) 상속 : 하이브리드 상속은 두 가지 이상의 상속 유형을 결합하여 구현됩니다. 예: 계층적 상속과 다중 상속 결합.
아래 이미지는 계층적 상속과 다중 상속의 조합을 보여줍니다.

// C++ program for Hybrid Inheritance #include using namespace std; // base class class Vehicle { public: Vehicle() { cout << 'This is a Vehicle
'; } }; // base class class Fare { public: Fare() { cout << 'Fare of Vehicle
'; } }; // first sub class class Car : public Vehicle { }; // second sub class class Bus : public Vehicle, public Fare { }; // main function int main() { // Creating object of sub class will // invoke the constructor of base class. Bus obj2; return 0; }> 산출
This is a Vehicle Fare of Vehicle>C++
// Example: #include using namespace std; class A { protected: int a; public: void get_a() { cout << 'Enter the value of 'a' : '; cin>>아; } }; 클래스 B : 공개 A { 보호: int b; 공개: 무효 get_b() { cout<< 'Enter the value of 'b' : '; cin>>b; } }; 클래스 C { 보호: int c; 공개: 무효 get_c() { cout<< 'Enter the value of c is : '; cin>>ㄷ; } }; 클래스 D : 공개 B, 공개 C { 보호: int d; 공개: void mul() { get_a(); get_b(); get_c(); 시합<< 'Multiplication of a,b,c is : ' <
라제쉬 칸나
6. 하이브리드 상속의 특별한 경우: 다중 경로 상속 :
두 개의 기본 클래스가 있는 파생 클래스와 이 두 기본 클래스가 하나의 공통 기본 클래스를 갖는 것을 다중 경로 상속이라고 합니다. 이러한 유형의 상속에서는 모호성이 발생할 수 있습니다.
예:
// C++ program demonstrating ambiguity in Multipath // Inheritance #include using namespace std; class ClassA { public: int a; }; class ClassB : public ClassA { public: int b; }; class ClassC : public ClassA { public: int c; }; class ClassD : public ClassB, public ClassC { public: int d; }; int main() { ClassD obj; // obj.a = 10; // Statement 1, Error // obj.a = 100; // Statement 2, Error obj.ClassB::a = 10; // Statement 3 obj.ClassC::a = 100; // Statement 4 obj.b = 20; obj.c = 30; obj.d = 40; cout << ' a from ClassB : ' << obj.ClassB::a; cout << '
a from ClassC : ' << obj.ClassC::a; cout << '
b : ' << obj.b; cout << '
c : ' << obj.c; cout << '
d : ' << obj.d << '
'; }> 산출
a from ClassB : 10 a from ClassC : 100 b : 20 c : 30 d : 40>
위의 예에서 ClassB와 ClassC는 모두 ClassA를 상속하며 둘 다 ClassA의 단일 복사본을 갖습니다. 그러나 Class-D는 ClassB와 ClassC를 모두 상속하므로 Class-D에는 ClassB와 ClassC의 두 가지 ClassA 복사본이 있습니다.
Class-D 객체를 통해 ClassA의 데이터 멤버에 액세스해야 하는 경우 ClassB 또는 ClassC에서 액세스할 경로를 지정해야 합니다. bcoz 컴파일러는 ClassA의 두 복사본을 구별할 수 없습니다. D등급.
이러한 모호함을 피하는 방법에는 두 가지가 있습니다.
1) 범위 확인 연산자를 사용하여 모호함을 피합니다. 위 예의 문 3과 4에 표시된 것처럼 범위 확인 연산자를 사용하여 데이터 멤버 a에 액세스할 경로를 수동으로 지정할 수 있습니다.
CPP obj.ClassB::a = 10; // Statement 3 obj.ClassC::a = 100; // Statement 4>
메모: 그래도 Class-D에는 ClassA의 복사본이 두 개 있습니다.
2) 가상 기본 클래스를 사용하여 모호함을 피합니다.
#include class ClassA { public: int a; }; class ClassB : virtual public ClassA { public: int b; }; class ClassC : virtual public ClassA { public: int c; }; class ClassD : public ClassB, public ClassC { public: int d; }; int main() { ClassD obj; obj.a = 10; // Statement 3 obj.a = 100; // Statement 4 obj.b = 20; obj.c = 30; obj.d = 40; cout << '
a : ' << obj.a; cout << '
b : ' << obj.b; cout << '
c : ' << obj.c; cout << '
d : ' << obj.d << '
'; }> 산출:
a : 100 b : 20 c : 30 d : 40>
위의 예에 따르면 Class-D에는 ClassA의 복사본이 하나만 있으므로 명령문 4는 명령문 3에 지정된 a의 값을 덮어씁니다.