How can I create objects while adding them into a vector?

前端 未结 5 735
星月不相逢
星月不相逢 2020-12-02 09:13

I have a C++ vector. I want the vector to hold a variable number of objects.

Visual Studio 2012 is giving me an error:

Error: type name is not all         


        
5条回答
  •  离开以前
    2020-12-02 09:42

    I know the thread is already all, but as I was checking through I've come up with a solution (code listed below). Hope it can help.

    #include 
    #include 
    
    class Box
    {
        public:
    
        static int BoxesTotal;
        static int BoxesEver;
        int Id;
    
        Box()
        {
            ++BoxesTotal;
            ++BoxesEver;
            Id = BoxesEver;
            std::cout << "Box (" << Id << "/" << BoxesTotal << "/" << BoxesEver << ") initialized." << std::endl;
        }
    
        ~Box()
        {
            std::cout << "Box (" << Id << "/" << BoxesTotal << "/" << BoxesEver << ") ended." << std::endl;
            --BoxesTotal;
        }
    
    };
    
    int Box::BoxesTotal = 0;
    int Box::BoxesEver = 0;
    
    int main(int argc, char* argv[])
    {
        std::cout << "Objects (Boxes) example." << std::endl;
        std::cout << "------------------------" << std::endl;
    
        std::vector  BoxesTab;
    
        Box* Indicator;
        for (int i = 1; i<4; ++i)
        {
            std::cout << "i = " << i << ":" << std::endl;
            Box* Indicator = new(Box);
            BoxesTab.push_back(Indicator);
            std::cout << "Adres Blowera: " <<  BoxesTab[i-1] << std::endl;
        }
    
        std::cout << "Summary" << std::endl;
        std::cout << "-------" << std::endl;
        for (int i=0; i<3; ++i)
        {
            std::cout << "Adres Blowera: " <<  BoxesTab[i] << std::endl;
        }
    
        std::cout << "Deleting" << std::endl;
        std::cout << "--------" << std::endl;
        for (int i=0; i<3; ++i)
        {
            std::cout << "Deleting Box: " << i+1 << " (" <<  BoxesTab[i] << ") " << std::endl;
            Indicator = (BoxesTab[i]);
            delete(Indicator);
        }
    
        return 0;
    }
    

    And the result it produces is:

    Objects (Boxes) example.
    ------------------------
    i = 1:
    Box (1/1/1) initialized.
    Adres Blowera: 0xdf8ca0
    i = 2:
    Box (2/2/2) initialized.
    Adres Blowera: 0xdf8ce0
    i = 3:
    Box (3/3/3) initialized.
    Adres Blowera: 0xdf8cc0
    Summary
    -------
    Adres Blowera: 0xdf8ca0
    Adres Blowera: 0xdf8ce0
    Adres Blowera: 0xdf8cc0
    Deleting
    --------
    Deleting Box: 1 (0xdf8ca0) 
    Box (1/3/3) ended.
    Deleting Box: 2 (0xdf8ce0) 
    Box (2/2/3) ended.
    Deleting Box: 3 (0xdf8cc0) 
    Box (3/1/3) ended.
    

提交回复
热议问题