casting - How can I remove the number associated with typeid( ).name( ) in C++? -
i have factory method class generates "items" , returns pointer item creates.
i have derived classes of item. example, item can "weapon" "consumable" or "armor."
i need detect type of item created can cast item type. did test lines , looks it's doing want, except adding number associated type.
example:
i had line:
cout << "type created: " << typeid(pitem).name() << endl;
which return base class item, display: "4item"
i changed to:
cout << "type created: " << typeid(*pitem).name() << endl;
which give me correct derived type, throw in number. "5armor"
why did pitem return base class? , why return int type? how can remove int?
a solution want - in "cheating" kind of way:
string type; string returnedtype = typeid(*pitem1).name(); (int i=1; < returnedtype.length(); i++){ type.push_back(returnedtype[i]); } cout << "type: " << type << endl;
thanks
you shouldn't use type-codes , switch/downcasts this. instead, put object-specific code virtual method or (depending on problem @ hand) use visitor pattern. current approach in end:
int price = 0; if (obj->get_type_str() == "armor") { price = 1000 + ((armor *)obj)->get_durability() * 100; } else if (obj->get_type_str() == "ninjasword") { price = 5000 * ((ninjasword *)obj)->get_damage(); } else if (obj->get_type_str() == "bfg") { price = 20000; } shop->show_price(price);
the problem is, isn't extensible. instead of defining price of object along object, littered around code. better way provide virtual method get_price(), can this:
class gameobject { public: virtual ~gameobject() {} virtual int get_price() const = 0; }; class armor: public gameobject { public: virtual int get_price() const { return 1000 + durability * 100; } private: int durability; }; class ninjasword: public gameobject { public: virtual int get_price() const { return 5000 * damage; } private: int damage; }; class bfg: public gameobject { public: virtual int get_price() const { return 20000; } };
now object-specific code stays in object , previous code example becomes:
shop->show_price(obj->get_price());
if code in question doesn't belong object, may case visitor pattern.
Comments
Post a Comment