C++/CLIをつつく17-多態性。曖昧なものを具体化。
public ref class Animal abstract
{
private:
Int32 m_age;
String^ m_name;
Animal(){}
public:
property Int32 Age {
Int32 get() { return this->m_age; }
void set( Int32 value ) {
if ( value > 0 ) m_age = value;
}
}
property String^ Name;
Animal ( String^ name, Int32 age ) {
this->Name = name;
this->Age = age;
}
void Talk( ) {
Console::WriteLine( "私は{0}。年は{1}だよ。",
this->Name, this->Age);
}
//ここに機能を追加
virtual void Move() abstract;
};
さっそくこのコードをコンパイルしてね。 コンパイルしたら・・・
警告 1 warning C4570: 'Sample::Bird' : 明示的に抽象として宣言されていませんが、抽象関数を含んでいます
警告 2 warning C4570: 'Sample::Human' : 明示的に抽象として宣言されていませんが、抽象関数を含んでいます
エラー 3 error C2259: 'Sample::Bird' : 抽象クラスをインスタンス化できません。
エラー 4 error C2259: 'Sample::Bird' : 抽象クラスをインスタンス化できません。
とC++/CLIコンパイラに怒られるピヨ。でも、これでいいんだ。 こうすることによって、新しいDogクラスとかを作る際にMoveメソッドの実装を忘れないで済むんだ。
C++/CLIコンパイラに怒られたからMoveメソッドを実装してみよう。
public ref class Bird : Animal
{
public:
Bird ( String^ name, Int32 age ) : Animal( name, age ) { }
virtual void Move() override {
Console::WriteLine( "バサバサバサバサ" );
}
};
public ref class Human : Animal
{
public:
Human ( String^ name, Int32 age ) : Animal( name, age ) { }
virtual void Move() override {
Console::WriteLine( "テクテクテクテク" );
}
};
using namespace Sample;
int main(array< System::String ^> ^args)
{
Bird^ tori = gcnew Bird( "インドリ", 29);
tori->Move( );
Console::WriteLine( "{0}参上!", tori->Name);
tori->Talk( );
Console::WriteLine( );
Human^ dre = gcnew Human( "ドリィちゃん", 16 );
dre->Move( );
Console::WriteLine( "{0}参上!", dre->Name );
dre->Talk( );
Console::WriteLine( );
return 0;
}
このコードを実行してごらん。同じ同じMoveメソッドでも実行結果が違うピヨ。
これが多態性(ポリモーフィズム)なんだ。突然だけど、長すぎると読みにくいので次回へ続く。