1 #include <iostream>  
 2 
 3 
 4 using namespace std;
 5 
 6 class A
 7 {
 8 public:
 9     A() { cout << "构造A!" << endl; };
10     virtual ~A() { cout << "析构A!" << endl; };
11 
12     virtual void DoSomething() { cout << "A的DoSomething!" << endl; };
13 };
14 
15 class B : public A
16 {
17 public:
18     B() { cout << "构造B!" << endl; };
19     ~B() { cout << "析构B!" << endl; };
20 
21     void DoSomething() { cout << "B的DoSomething!" << endl; };
22 };
23 
24 int main()
25 {
26     A *Test1 = new A;
27     cout << "**************" << endl;
28     Test1->DoSomething();
29     cout << "**************" << endl;
30     delete Test1;
31     cout << "**************" << endl;
32     B *Test2 = new B;
33     cout << "**************" << endl;
34     Test2->DoSomething();
35     cout << "**************" << endl;
36     delete Test2;
37     cout << "**************" << endl;
38     A *Test3 = new B;
39     cout << "**************" << endl;
40     Test3->DoSomething();
41     cout << "**************" << endl;
42     delete Test3;
43     return 0;
44 }
View Code

运行结果:

修改代码,删除virtual

 1 #include <iostream>  
 2 
 3 
 4 using namespace std;
 5 
 6 class A
 7 {
 8 public:
 9     A() { cout << "构造A!" << endl; };
10      ~A() { cout << "析构A!" << endl; };
11 
12     virtual void DoSomething() { cout << "A的DoSomething!" << endl; };
13 };
14 
15 class B : public A
16 {
17 public:
18     B() { cout << "构造B!" << endl; };
19     ~B() { cout << "析构B!" << endl; };
20 
21     void DoSomething() { cout << "B的DoSomething!" << endl; };
22 };
23 
24 int main()
25 {
26     A *Test1 = new A;
27     cout << "**************" << endl;
28     Test1->DoSomething();
29     cout << "**************" << endl;
30     delete Test1;
31     cout << "**************" << endl;
32     B *Test2 = new B;
33     cout << "**************" << endl;
34     Test2->DoSomething();
35     cout << "**************" << endl;
36     delete Test2;
37     cout << "**************" << endl;
38     A *Test3 = new B;
39     cout << "**************" << endl;
40     Test3->DoSomething();
41     cout << "**************" << endl;
42     delete Test3;
43     return 0;
44 }
View Code

运行结果:

如果是是

B b;

结果:

 

posted on 2015-06-08 18:28  Xpecial  阅读(126)  评论(0)    收藏  举报