How to create class objects dynamically?

后端 未结 3 2101
不知归路
不知归路 2020-12-08 01:13

Let\'s say I have a class box, and a user can create boxes. How to do it? I understand I create objects by className objectName(args); but how

3条回答
  •  [愿得一人]
    2020-12-08 01:57

    The following factory method creates Box instances dynamically based on user input:

    class BoxFactory
    {
      public:
        static Box *newBox(const std::string &description)
        {
          if (description == "pretty big box")
            return new PrettyBigBox;
          if (description == "small box")
            return new SmallBox;
          return 0;
        }
    };
    

    Of course, PrettyBigBox and SmallBox both derive from Box. Have a look at the creational patterns in the C++ design patterns wikibook, as one of them probably applies to your problem.

提交回复
热议问题