Menu
CoddyTech

仮想ディスパッチ

Coddyの「Lua開発者のためのC++」コースのレッスン 39/48。

Luaのメソッド呼び出しはすべて動的です。obj:label()は、呼び出し時にオブジェクト上でlabelを検索し、その後__indexテーブルのチェーンをたどるため、Childでのオーバーライドが常に優先され、Base.label(self)を明示的に呼び出すことで基本クラスのバージョンに到達します。C++ではこの動作にvirtualが必要で、基本クラスの値を使うときはスライシングを避けなければなりません。基本クラスのポインターまたは参照を通じたC++の仮想関数呼び出しは動的ディスパッチされます。ポリモーフィックな削除には仮想デストラクターが必要です。基本クラスの値へのコピーではスライシングが発生することがあります。

Lua

local Base = {}
Base.__index = Base
function Base.new()
  return setmetatable({}, Base)
end
function Base:label()
  return "base"
end
local Child = setmetatable({}, { __index = Base })
Child.__index = Child
function Child.new()
  return setmetatable({}, Child)
end
function Child:label()
  return Base.label(self) .. "!"
end
for _, item in ipairs({ Base.new(), Child.new() }) do
  print(item:label())
end

C++

#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>
struct Sound{virtual ~Sound()=default;virtual std::string play()const{return "tap";}};struct Chime:Sound{std::string play()const override{return "ding";}};
int main(){
Chime x;const Sound& s=x;std::cout<<s.play()<<"\n";
}

各プログラムをそれぞれ独立して追ってください。これらの例では、課題とは異なる操作やデータを使って概念を説明しています。ソースとターゲットの出力が一致するとは限りません。

challenge icon

チャレンジ

簡単

入力: 基本料金とボーナス。いずれも非負です。Fee.amount は基本料金を返します。ExtraFee は Fee を public 継承し、ボーナスを加算するよう amount をオーバーライドします。ドライバーは const Fee 参照を介して呼び出します。仮想デストラクターを使用してください。

編集可能なモジュール: Fee.cpp、Fee.hpp、ExtraFee.cpp、ExtraFee.hpp。必要な各型には、それぞれ名前付きのヘッダーと実装ファイルがあります。すべての public シグネチャを保持してください。ロックされた main.cpp は標準入力を読み取り、API を直接呼び出します。また、指定されている箇所では、public API の動作も独立して確認します。API 内で出力せず、値を返してください。整数の入力値と結果は signed int に収まり、特に指定がない限りテキストは ASCII です。

自分で試してみよう

#include "Fee.hpp"
#include "ExtraFee.hpp"
#include <iostream>
int main(){
{Fee a(5);ExtraFee b(2,7);const Fee& r=b;if(a.amount()!=5||r.amount()!=9)return 21;}
std::vector<std::string> rows; std::string line; while(std::getline(std::cin,line)) rows.push_back(line);
std::istringstream in(rows.empty()?"":rows[0]);int a,b;in>>a>>b;ExtraFee f(a,b);const Fee& ref=f;std::cout<<ref.amount()<<"\n";
}
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

Lua開発者のためのC++のすべてのレッスン

自分で練習してみよう: C++オンラインコンパイラ