Cpp クラス 継承 アップキャスト 新しいページはコチラ

提供: yonewiki
移動: 案内, 検索
(クラス 継承 アップキャスト)
(クラス 継承 アップキャスト)
292行: 292行:
 
printf("Destructer:~CDeriveDiscountInheritance()\n");
 
printf("Destructer:~CDeriveDiscountInheritance()\n");
 
}
 
}
 
  
 
void CDeriveDiscountInheritance::mf_iDeriveSetDiscount(double dArgRate) {
 
void CDeriveDiscountInheritance::mf_iDeriveSetDiscount(double dArgRate) {
302行: 301行:
 
printf("DeriveMoney=%d\n", iSumMoney);
 
printf("DeriveMoney=%d\n", iSumMoney);
 
}
 
}
 +
</syntaxhighlight2>
  
 +
 コンストラクタCDeriveDiscountInheritance(int iArgMoney, int iArgMonth, double dArgRate)は3つめの引数で割引の率を受け取ります。5割引きなら0.5を受け付ける形式です。50%の50とかではないです。そして、割合をm_dRateへ格納します。2つの引数だけ受け取るコンストラクタを使って、後から割合だけを受け取るCDeriveDiscountInheritance::mf_iDeriveSetDiscountというメンバ関数もあります。そしてCDeriveDiscountInheritance::mf_vDeriveDiscountDispValue()で割引した後の金額を表示します。m_dRateはdouble型なので、計算結果が小数まで計算されます。これを四捨五入するために0.5を足して、(int)(計算結果小数)のようにキャストして小数部を切り落としています。通常のお店の計算では四捨五入ではなく、切り捨てされるのが普通ですが、あえて四捨五入にしてみました。小数点第何位や十、百、千の位とかで四捨五入する場合はもっと違うカタチで四捨五入をしなければならないです。ひとつの方法としては、四捨五入する位置が小数第一位に持ってくるようにを一度、10のN乗倍してから、上記と同じ方法で切り落として、そしてもう一度 10の-N乗倍して、元に戻すという感じです。これだと桁あふれや桁落ちが発生しやすいので、別の方法の方が良かったりします。で、いろいろ考えて自分で作ろうとしてしまいがちですが、標準関数で四捨五入をする関数が既に用意されていたりもします。
  
  
 +
 これで派生クラスも出そろいました。普通に派生クラスを利用しようとすると以下のようになります。
  
 +
<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"
  
 +
int main() {
 +
 +
    CBaseInheritance objCBaseInheritance(3900, 12);
 +
    objCBaseInheritance.mf_vBaseDispValue();
 +
 +
    CDeriveInheritance objCDeriveInheritance2Arg(2900, 12);
 +
    objCDeriveInheritance2Arg.mf_vDeriveSetOptionValue(600);
 +
    objCDeriveInheritance2Arg.mf_vDeriveDispValue();
 +
 +
    CDeriveInheritance objCDeriveInheritance3Arg(2900, 12, 600);
 +
    objCDeriveInheritance3Arg.mf_vDeriveDispValue();
 +
 +
    int piOptionArr[] = { 300, 500, 400, 390 };
 +
    int iSize = (int)(sizeof piOptionArr / sizeof(*piOptionArr));
 +
    CDeriveArrInheritance objCDeriveArrInheritance(3900, 12, piOptionArr, iSize);
 +
    objCDeriveArrInheritance.mf_vDeriveArrDispValue();
 +
 +
    CDeriveDiscountInheritance objCDeriveDiscountInheritance(3900, 12, 0.5);
 +
    objCDeriveDiscountInheritance.mf_vDeriveDiscountDispValue();
 +
 +
    return 0;
 +
 +
}
 
</syntaxhighlight2>
 
</syntaxhighlight2>
  
 
[[C PlusPlus#C++からの技術|C++]]に戻る
 
[[C PlusPlus#C++からの技術|C++]]に戻る

2020年7月23日 (木) 00:00時点における版



個人用ツール
名前空間

変種
操作
案内
ツールボックス