静态绑定和动态绑定(多态)

scorlw 发布于

静态绑定和动态绑定(多态)

c++

1、对象的静态类型(static type):就是它在程序中被声明时所采用的类型(或理解为类型指针或引用的字面类型),在编译期确定;

2、对象的动态类型(dynamic type):是指“目前所指对象的类型”(或理解为类型指针或引用的实际类型),在运行期确定;

这两个概念一般发生在基类和派生类之间。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Base
{
public:
int a;
Base()
{
a = 1;
cout << "Base()" << endl;
}
~Base()
{
cout << "~Base()" << endl;
}
};

class Derived : public Base
{
public:
int b;
Derived()
{
b = 2;
cout << "Derived()" << endl;
}
~Derived()
{
cout << "~Derived()" << endl;
}
};

int main()
{
Base *pB = new Derived(); //pB的静态类型为Base, 动态类型为Derived;
delete pB;
}

3、静态绑定(statically bound):又名前期绑定(eraly binding),绑定的是静态类型,所对应的函数或属性依赖于对象的静态类型,发生在编译期;

4、动态绑定(dynamically bound):又名后期绑定(late binding),绑定的是动态类型,所对应的函数或属性依赖于对象的动态类型,发生在运行期;

一般的,virtual函数是动态绑定,non-virtual函数是静态绑定,缺省参数值也是静态绑定

所以~Base()函数是静态绑定的,所以输出结果(delete时会调用析构函数)是:

1
2
3
Base();
Derived();
~Base();

但将基类析构函数改为虚函数时,即:

1
2
3
4
5
6
7
8
9
10
11
12
public:
int a;
Base()
{
a = 1;
cout << "Base()" << endl;
}
virtual ~Base()
{
cout << "~Base()" << endl;
}
};

现在输出结果是:

1
2
3
4
Base();
Derived();
~Derived();
~Base();

原文地址:https://blog.csdn.net/u010757019/article/details/83153792