内容:
说明:
dynamic_cast的使用
示例代码:
// Magic_Spells.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <string> #include <iostream> using namespace std; class Spell { private: string scrollName; public: Spell() : scrollName( "" ) { } Spell( string name ) : scrollName( name ) { } virtual ~Spell() { } string revealScrollName() { return scrollName; } }; class Fireball : public Spell { private: int power; public: Fireball( int power ) : power( power ) { } void revealFirepower() { cout << "Fireball: " << power << endl; } }; class Frostbite : public Spell { private: int power; public: Frostbite( int power ) : power( power ) { } void revealFrostpower() { cout << "Frostbite: " << power << endl; } }; class Thunderstorm : public Spell { private: int power; public: Thunderstorm( int power ) : power( power ) { } void revealThunderpower() { cout << "Thunderstorm: " << power << endl; } }; class Waterbolt : public Spell { private: int power; public: Waterbolt( int power ) : power( power ) { } void revealWaterpower() { cout << "Waterbolt: " << power << endl; } }; class SpellJournal { public: static string journal; static string read() { return journal; } }; string SpellJournal::journal = ""; void counterspell( Spell *spell ) { if( Fireball * fool = dynamic_cast<Fireball*>( spell ) ) { fool->revealFirepower(); } else if( Frostbite * fros = dynamic_cast<Frostbite*>( spell ) ) { fros->revealFrostpower(); } else if( Thunderstorm * thud = dynamic_cast<Thunderstorm*>( spell ) ) { thud->revealThunderpower(); } else if( Waterbolt * water = dynamic_cast<Waterbolt*>( spell ) ) { water->revealWaterpower(); } else { string spellWord = spell->revealScrollName(); string journal = SpellJournal::read(); int** array = new int*[spellWord.length() + 1]; for( int i = 0; i < spellWord.length() + 1; i++ ) { array[i] = new int[journal.length() + 1]; for( int j = 0; j < journal.length() + 1; j++ ) { if( i == 0 || j == 0 ) { array[i][j] = 0; } else { if( spellWord[i - 1] == journal[j - 1] ) { array[i][j] = array[i - 1][j - 1] + 1; } else { array[i][j] = ( array[i - 1][j] > array[i][j - 1] ) ? array[i - 1][j] : array[i][j - 1]; } } } } cout << array[spellWord.length()][journal.length()] << endl; } } class Wizard { public: Spell *cast() { Spell *spell; string s; cin >> s; int power; cin >> power; if( s == "fire" ) { spell = new Fireball( power ); } else if( s == "frost" ) { spell = new Frostbite( power ); } else if( s == "water" ) { spell = new Waterbolt( power ); } else if( s == "thunder" ) { spell = new Thunderstorm( power ); } else { spell = new Spell( s ); cin >> SpellJournal::journal; } return spell; } }; //by zhaocl int main() { int T; cin >> T; Wizard Arawn; while( T-- ) { Spell *spell = Arawn.cast(); counterspell( spell ); } system( "pause" ); return 0; }
知识点:
dynamic_cast运算符的主要用途:将基类的指针或引用安全地转换成派生类的指针或引用,并用派生类的指针或引用调用非虚函数。如果是基类指针或引用调用的是虚函数无需转换就能在运行时调用派生类的虚函数。
前提条件:当我们将dynamic_cast用于某种类型的指针或引用时,只有该类型含有虚函数时,才能进行这种转换。否则,编译器会报错。