How to create class objects dynamically?

后端 未结 3 2103
不知归路
不知归路 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:51

    In C++, it is possible to allocate objects using automatic (stack) and dynamic (heap) storage.

    Type variable_name; // variable_name has "automatic" storage.
                        // it is a local variable and is created on the stack.
    
    Type* pointer_name = NULL; // pointer_name is a "pointer". The pointer, itself,
                               // is a local variable just like variable_name
                               // and is also created on the stack. Currently it
                               // points to NULL.
    
    pointer_name = new DerivedType; // (where DerivedType inherits from Type). Now
                                    // pointer_name points to an object with
                                    // "dynamic" storage that exists on the heap.
    
    delete pointer_name; // The object pointed-to is deallocated.
    pointer_name = NULL; // Resetting to NULL prevents dangling-pointer errors.
    

    You can use pointers and heap-allocation to dynamically construct objects as in:

    #include 
    #include 
    #include 
    class Base {
        public:
            virtual ~Base(){}
            virtual void printMe() const = 0;
        protected:
            Base(){}
    };
    class Alpha : public Base {
         public:
            Alpha() {}
            virtual ~Alpha() {}
            virtual void printMe() const { std::cout << "Alpha" << std::endl; }
    };
    class Bravo : public Base {
         public:
            Bravo() {}
            virtual ~Bravo() {}
            virtual void printMe() const { std::cout << "Bravo" << std::endl; }
    };
    int main(int argc, char* argv[]) {
        std::auto_ptr pointer; // it is generally better to use boost::unique_ptr,
                                     // but I'll use this in case you aren't familiar
                                     // with Boost so you can get up and running.
        std::string which;
        std::cout << "Alpha or bravo?" << std::endl;
        std::cin >> which;
        if (which == "alpha") {
            pointer.reset(new Alpha);
        } else if (which == "bravo") {
            pointer.reset(new Bravo);
        } else {
            std::cerr << "Must specify \"alpha\" or \"bravo\"" << std::endl;
            std::exit(1);
        }
        pointer->printMe();
        return 0;
    }
    

    Related: the "Factory" object-oriented design pattern

提交回复
热议问题