C++11新特性(三)Strongly-typed enums 強類型枚舉簡單使用


#include <iostream>

enumclass KObjectType

{

    KPlayerType,

    kMonsterType,

    kNPCType,

    KObjectTypeCount,

};



class Node

{

public:

   virtual void setType(KObjectType type) = 0;

   virtual  KObjectType getType()const = 0;

   virtual ~Node(){};

   virtual void showType() {};

};

class Player :public Node

{

public:

   virtual void setType(KObjectType type) override;

   virtual  KObjectType  getType()const override;

   virtual void showType() override {std::cout <<" PlayerType" << std::endl;};

    

private:

   KObjectType m_enType_;

};

voidPlayer::setType(KObjectType type)

{

   m_enType_ = type;

}



KObjectType  Player::getType()const

{

    returnm_enType_;

}



class Monster :public Node

{

public:

   virtual void setType(KObjectType type) override;

   virtual  KObjectType  getType()const override;

   virtual void showType() override {std::cout <<" MonsterType" << std::endl;};


private:

   KObjectType m_enType_;



};



void Monster::setType(KObjectType type)

{

   m_enType_ = type;

}



KObjectType  Monster::getType()const

{

    returnm_enType_;

}



class FactoryCreation

{

    

public:

   static Node* create(KObjectType type);

    

};


Node* FactoryCreation::create(KObjectType type)

{

   Node *object = nullptr;

    

   switch (type) {

            

       case KObjectType::KPlayerType:

            object =new Player();

           break;


       case KObjectType::kMonsterType:

            object =new Monster();

           break;

       default:

           break;

    }

   if (object) {

        object->setType(type);

        

    }

    

   return object;

}


int main()

{

    

    auto p =FactoryCreation::create(KObjectType::KPlayerType);

    p->showType();

   delete p;

    

    

    auto m =FactoryCreation::create(KObjectType::kMonsterType);

    m->showType();

   delete m;    

   return 0;

}


結果輸出如下:

PlayerType

 MonsterType

Program ended with exit code: 0


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章