横刀立马0

导航

作用域

 1 #include <iostream>
 2 using namespace std;
 3 class A
 4 {
 5     public:
 6     A(int i = 0)
 7     {
 8         num = i;
 9         cout << "A()" << num << endl;
10     }
11     ~A() 
12     {
13         cout << "~A()" << num << endl;
14     }
15     private:
16     int num;
17 };
18 class B
19 {
20     public:
21     B()
22     {
23         cout << "B()" << endl;
24     }
25     ~B() 
26     {
27         cout << "~B()"<< endl;
28     }
29 };
30 
31 int main()
32 {
33     {A a1;}
34     A a2(1);
35     B b;
36     A *p = new A[2]{2,3};
37     delete [] p;
38    return 0;
39 }

结果是:

 1 A()0
 2 ~A()0
 3 A()1
 4 B()
 5 A()2
 6 A()3
 7 ~A()3
 8 ~A()2
 9 ~B()
10 ~A()1

加了{},就圈定了作用域,对象只在作用域内有效

posted on 2019-06-19 15:19  横刀立马0  阅读(55)  评论(0编辑  收藏  举报