C++ Determine if class can use an object - text RPG game

前端 未结 4 1017
有刺的猬
有刺的猬 2021-01-25 18:58

I\'m facing with the following design problem:

TL;TD need to determine if Hero(class) can use specific object while there\'s many heroes implementations

I have

4条回答
  •  礼貌的吻别
    2021-01-25 19:36

    You could use dynamic_cast<>() to determine the type of your Hero pointer, like so:

    Hero *h;
    Weapon * i;
    // do something assign values
    if(dynamic_cast != nullptr)
        h->use(i);
    

    where HeroSubClass is the particular subclass of Hero that you want to check for (Warrior, etc.). If your Hero * is not a pointer to an object of class HeroSubClass, dynamic_cast will return nullptr, if it is, it will return a HeroSubClass *.

    Alternatively, you could just check the type of the Weapon * within use() for each HeroSubClass, and perhaps print out something like "Warrior cannot use Staff" if it's an object of the wrong class.

提交回复
热议问题