析构函数 p157

析构函数

确保对象的各部分被正确的清除,及做一些用户指定的其他清理工作。

当对象超出它的作用域时,编译器将自动调用析构函数;手动用new在堆上分配的对象空间,需要调用'delete 对象地址'进行手动清除, delete 语句 先调用该对象的析构函数,然后释放内存

 

 1 #include <iostream>
 2 #include <string>
 3 
 4 using namespace std;
 5 
 6 
 7 class Publisher
 8 {
 9     string name;
10     string address;
11     string telephone;
12 
13 public:
14     
15     Publisher(string name, string address, string telephone) : name(name), address(address), telephone(telephone) 
16     {
17         cout << "Publisher(string name, string address, string telephone)" << endl;
18     }
19 
20     ~Publisher()
21     {
22         cout << "~Publisher()" << endl;
23     }
24 
25     friend ostream& operator<<(ostream& os, const Publisher& p)
26     {
27         return os << "PublisherName: " << p.name << ", PublisherAddress: " << p.address << ", Publishertelephone: " << p.telephone;
28     }
29 
30 };
31 
32 
33 class Book
34 {
35     string name;
36     string author;
37     double price;
38     Publisher* publisher;
39 
40 public:
41 
42     Book(string name, string author, double price, Publisher* pub) : name(name), author(author), price(price), publisher(pub)
43     {
44         cout << "Book(string name, string author, double price, Publisher publisher)" << endl;
45     }
46 
47     ~Book()
48     {
49         cout << "~Book()" << endl;
50         if (publisher != 0)
51         {
52             delete publisher;
53             publisher = 0;
54             cout << "delete publisher" << endl;
55         }    
56     
57     }
58 
59     friend ostream& operator<<(ostream& os, const Book& b)
60     {
61          os << "-------- print Book ---------------" << endl;
62          os << "BookName: " << b.name << ", BookAuthor: " << b.author << ", BookPrice: " << b.price << endl;;
63          os << *b.publisher << endl;;
64          return os;
65     }
66 
67 };
68 
69 int main()
70 {
71     
72     Publisher* pub = new Publisher("人民出版社", "北京市西城区", "021-2134343545");
73 
74     Book b1("算法精解", "Kyle Loudon", 56.2, pub);
75 
76     cout << b1 << endl;
77 
78 };

 

运行结果:

 

posted @ 2015-06-27 21:04  asnjudy  阅读(188)  评论(0编辑  收藏  举报