将对象添加到对象数组

时间:2018-02-24 20:49:31

标签: c++ arrays

我在将案例book中的对象添加到book数组时遇到了一些困难,这是我目前为止的代码。

book *library;
cout << "What would you like the size of the library to be? ";
cin >> num;
library = new book [num];

book *newBook = new book ();   //Default constructor 

for (int i = 0; i <= num; i++)
{
    library[i] = *newBook; // I am getting Access violation writing location
}

我希望我可以使用Vector,但我无法完成这项任务。

1 个答案:

答案 0 :(得分:1)

访问冲突是因为for循环超过了数组的末尾。还有其他问题&#34;。库中的每本书都是在循环外分配new的书的副本。没有理由使用new来分配书籍,人们会认为每本书都应该单独构建,而不是从一本书中复制。并且......存在内存泄漏。

这可能会让老师满意:

#include <iostream>

class book
{};

int main()
{
    int num = 0;
    std::cout << "What would you like the size of the library to be? ";
    std::cin >> num;
    book *library = new book[num]; // Sigh

    for (int i = 0; i < num; ++i)
    {
        library[i] = book(); // Unnecessary. Books are already default-constructed
    }

    delete[] library;  // Sigh again.
    return 0;
}