コンテンツにスキップ

継承 (プログラミング)

出典: フリー百科事典『ウィキペディア(Wikipedia)』

: inheritance

OOPOOP[1]

[]


delegation1concatenation



inheritancesubtyping/substitute使/substitutability

 ()Is-aHas-aIs-aHas-a使

[]

[]


difference coding使


サブタイピング[編集]


subtypingsubstitutabilityIs-a

implementation inheritancecode inheritanceinterface inheritance

Is-aUML/UML/


#include <iostream>
#include <string>
#include <typeinfo>

class Base {
public:
    virtual ~Base() {}
    virtual std::string greet() const = 0;
};

class Derived : public Base {
    virtual ~Derived() { std::cout << "Destructor of Derived is called." << std::endl; }
    virtual std::string greet() const { return "Hello!"; }
};

int main() {
    Base* b = new Derived(); // OK
    std::cout << "Message: " << b->greet() << std::endl;
    std::cout << "Is instance of Derived? " << std::boolalpha << (typeid(*b) == typeid(Derived)) << std::endl;
    delete b;
    return 0;
}

多重継承[編集]


MROMRO

C++/EiffelEiffelPythonC3

12
class Base {
public:
    int n;
};

// 非仮想継承。
class DerivedNV1 : public Base { /* ... */ };
class DerivedNV2 : public Base { /* ... */ };

// 仮想継承。
class DerivedV1 : public virtual Base { /* ... */ };
class DerivedV2 : public virtual Base { /* ... */ };

class DerivedNV : public DerivedNV1, public DerivedNV2 { /* ... */ };
class DerivedV : public DerivedV1, public DerivedV2 { /* ... */ };

int main() {
    DerivedNV nv;
    //nv.n = 0; // 曖昧さが解決できないためコンパイルエラー。
    nv.DerivedNV1::n = 0;
    nv.DerivedNV2::n = 0;
    DerivedV v;
    v.n = 0; // コンパイルエラーにはならない。
    return 0;
}



DerivedNVDerivedNV1Base::nDerivedNV2Base::n2nDerivedVBase1DerivedV1DerivedV2

OOPC++EiffelJavaC#

(一)

(二)

(三)

(四)使

使

[]


public/protected/package/privateprivatepackage

/

(一)public - 

(二)protected - publicprotected

(三)private - public/protectedprivate

C++OOP

ミックスイン[編集]


Mix-in1/

Mix-in

Mix-in

Mix-in

Mix-in1

Mix-in

this使Mix-inThis


UML[]


 (UML)  (generalization)  (specialization) 

realization[]implementation

//UML

脚注[編集]

  1. ^ MDN contributors (2022年9月17日). "継承とプロトタイプチェーン - JavaScript". developer.mozilla.org. 2022年9月18日閲覧

関連項目[編集]