在这种情况下,我想删除这本书,但我尝试声明此代码,但它不起作用。
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/