Question 10: Given the following program snippet, what can we conclude about the use of dynamic_cast in C++?

#include <iostream> #include <memory> //Someone else's code, e.g. library class IGlyph { public: virtual ~IGlyph(){} virtual std::string Text()=0; virtual IIcon* Icon()=0; //... }; class IWidgetSelector { public: virtual ~IWidgetSelector(){} virtual void AddItem(IGlyph*)=0; virtual IGlyph* Selection()=0; }; //Your code class MyItem : public IGlyph { public: virtual std::string Text() { return this->text; } virtual IIcon* Icon() { return this->icon.get(); } void Activate() { std::cout << "My Item Activated" << std::endl; } std::string text; std::auto_ptr<IIcon> icon; }; void SpiffyForm::OnDoubleClick(IWidgetSelector* ws) { IGlyph* gylph = ws->Selection(); MyItem* item = dynamic_cast<MyItem*>(gylph); if(item) item->Activate(); }

 

    A. The dynamic_cast ought to be a reinterpret_cast since the concrete type is unknown.

    B. The dynamic_cast is unnecessary since we know that the concrete type returned by IWidgetSelector::Selection() must be a MyItem object.

    C. The dynamic_cast is redundant, the programmer can invoke Activate directly, e.g. ws->Selection()->Activate();

    D. The dynamic_cast is necessary since we cannot know for certain what concrete type is returned by IWidgetSelector::Selection().

    E. A polymorphic_cast should be used in place of the dynamic_cast.

 

D

你可能感兴趣的:(C++,String,Class,include)