Cpp クラス 継承 アップキャスト 新しいページはコチラ
提供: yonewiki
(→クラス 継承 アップキャスト) |
(→クラス 継承 アップキャスト) |
||
402行: | 402行: | ||
− | + | で、これを元にアップキャストって奴をやってみようと思います。こんな行き当たりばったりでサンプルを作っているので、上手いこと行くかはわかりませんが、メイン関数を作り直してみます。 | |
+ | |||
+ | <span style="color: #ffffff; background-color: #555555; padding: 0px 5px 0px 5px; display: inline-block;">cpp <span>(</span>メイン関数 InheritanceMain.cpp<span>)</span><!-- padding 上 右 下 左--> | ||
+ | <syntaxhighlight2 lang="cpp" line> | ||
+ | #include "pch.h" | ||
+ | #include "BaseInheritance.h" | ||
+ | #include "DeriveInheritance.h" | ||
+ | #include "DeriveArrInheritance.h" | ||
+ | #include "DeriveDiscountInheritance.h" | ||
+ | |||
+ | CBaseInheritance* pCBaseInheritanceUpcastF(int iSelectDerive) { | ||
+ | int piOptionUpcastArr[] = { 800, 200, 500, 220 }; | ||
+ | int iSize = (int)(sizeof piOptionUpcastArr / sizeof(*piOptionUpcastArr)); | ||
+ | switch (iSelectDerive) { | ||
+ | case 1: | ||
+ | return new CDeriveInheritance(2900, 12); | ||
+ | case 2: | ||
+ | return new CDeriveArrInheritance(2900, 12, piOptionUpcastArr, iSize); | ||
+ | default: | ||
+ | return new CDeriveDiscountInheritance(3900, 12, 0.5); | ||
+ | } | ||
+ | }; | ||
+ | |||
+ | int main() { | ||
+ | |||
+ | CBaseInheritance* pCBaseInheritanceUpcast; | ||
+ | pCBaseInheritanceUpcast = pCBaseInheritanceUpcastF(1); | ||
+ | pCBaseInheritanceUpcast->mf_vBaseDispValue(); | ||
+ | pCBaseInheritanceUpcast = pCBaseInheritanceUpcastF(2); | ||
+ | pCBaseInheritanceUpcast->mf_vBaseDispValue(); | ||
+ | pCBaseInheritanceUpcast = pCBaseInheritanceUpcastF(3); | ||
+ | pCBaseInheritanceUpcast->mf_vBaseDispValue(); | ||
+ | delete pCBaseInheritanceUpcast; | ||
+ | |||
+ | return 0; | ||
+ | |||
+ | } | ||
+ | </syntaxhighlight2> | ||
+ | |||
+ | このようにサンプルのメインプログラムだけを変えました。基底クラスのポインタ変数を作って、派生クラスを動かした結果を受け取っています。プログラムの中で、動かす派生クラスを選べて、基底クラスを利用するカタチにしてみました。派生クラスを生成するとオブジェクトが出来当たりますが、そのオブジェクトのポインタを返却(return)したときに関数の返却値の型が基底クラスのポインタ型になっています。そして、結果をそのままメイン関数で受け取るので、アップキャストはreturnの型から返却値の型に変換されているところで起こっています。 | ||
[[C PlusPlus#C++からの技術|C++]]に戻る | [[C PlusPlus#C++からの技術|C++]]に戻る |