delete 对象地址;
delete 首先调用待清除对象的析构函数,然后释放内存
如果delete一个void指针,唯一发生的事情就是释放了内存。因为通过void指针,无法知道对象的类型,就无法调用其析构函数。
delete []books;
[]告诉编译器,books实际上是一个对象数组的起始地址。该代码的任务是,把数组创建时存放在某处的数组元素个数取回,并为数组的所有对象调用析构函数。
1 #include <iostream> 2 #include <string> 3 4 using namespace std; 5 6 class Book 7 { 8 string name; 9 string author; 10 double price; 11 12 public: 13 Book() : name("null"), author("null"), price(0) {} 14 Book(string name, string author, double price) : name(name), author(author), price(price) {} 15 16 //复制构造函数 17 Book(const Book& b) : name(b.name), author(b.author), price(b.price) 18 { 19 cout << "Book::Book(const Book& b)" << endl; 20 } 21 22 ~Book() 23 { 24 cout << "~Book()" << endl; 25 cout << "释放书名为:‘" << name << "‘占用的内存" << endl; 26 } 27 28 friend ostream& operator<<(ostream& os, const Book& b) 29 { 30 return os << "BookName: " << b.name << ", BookAuthor: " << b.author 31 << ", BookPrice: " << b.price; 32 } 33 34 //重载赋值运算符 35 Book& operator=(const Book& b) 36 { 37 cout << "Book::operator=(const Book&)" << endl; 38 name = b.name; 39 author = b.author; 40 price = b.price; 41 42 return *this; 43 } 44 }; 45 46 47 int main() 48 { 49 //数组book里放的是Book类型的指针 -- 使用new在堆上创建对象数组 50 //在堆上为‘5个Book对象’分配了内存,并为这5个Book对象调用了构造函数 51 Book* books = new Book[5]; 52 53 Book* b1 = new Book("算法精解", "Kyle Loudon", 56.2); 54 Book* b2 = new Book("Qt程序设计", "Pulat", 10.2); 55 56 books[0] = *b1; // 57 books[1] = *b2; 58 59 cout << "---- delete b1 ----" << endl; 60 delete b1; 61 cout << "---- delete b2 ----" << endl; 62 delete b2; 63 64 cout << "---- delete []books ----" << endl; 65 delete []books; 66 67 return 0; 68 };
时间: 2024-10-09 22:59:43