c++ - 需要类中二维数组的帮助(C++)

标签 c++ arrays class pointers heap-memory

在这种情况下,我想删除这本书,但我尝试声明此代码,但它不起作用。

class Library {
private:
    Book **books;
    int counter;
public:
    Library() {
        books = NULL;
        counter = 0;
    }
    void Add(INPUT &tmp) {
        books = new Book*[counter];
        ++counter;
    }
    void Delete() {
        --counter;
        delete[] books[counter];
        books[counter] = NULL;
    }
    int getCounter() {
        return this->counter;
    }
    ~Library() {
        delete[] books;
    }
};

最佳答案

在开始删除之前,您需要正确添加。

除了 Jeffrey 所说的之外,您的 Add 函数可能由于“out by one”错误而无法正常工作。在第一次调用中,您将得到 books = new Book*[0];。分配大小为零的数组是合法的(请参阅 here ),但您将无法在其中存储任何内容。

如果您可以使用 std::vector,它将使您的代码更加简单且不易出错。

class Library {
private:
    std::vector<Book> books;
    // no need for counter, std::vector has size()
public:
    // no need for a constructor, the default constructor
    // will correctly construct 'books'
    void Add(INPUT &tmp) {
        // not sure how you convert 'INPUT' to 'Book'
        books.push_back(tmp);
        // this handles all of the memory management for you
    }
    void Delete() {
        // you need to ensure that books is not empty
        books.pop_back();
    }
    int getCounter() {
        return books.size();
    }
    // no need for a destructor, the default one will
    // do everything
};

如果您需要二维,则代码类似但将使用 vector 的 vector 。

关于c++ - 需要类中二维数组的帮助(C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52223711/

相关文章:

c++ - 如何使用 C++ 中的友元函数将成员变量从一个类访问到另一个类?

C++11 复杂<浮点>* 到 C 浮点复杂*

java - 从 ByteBuffer 获取到 byte[] 不会写入 byte[]

c++ - calloc vs new 用于各种编译器中的复杂结构

java - JTabbedPane 给出空指针异常

javascript - JS-textarea行到javascript数组

c# - 从类调用寻呼

ios - 如何制作 NSCountedSet 类的结构版本?

c++ - 来自系统存储的证书上下文始终具有无效的 pbCertEncoded 指针

c++ - 如何使用 C++ 绑定(bind) libpq 中的 NULL 值?