标题
- 还是写下来好了
1. C++的动态绑定和静态绑定
先说C++的静态类型和动态类型:
静态类型是指指针或者对象声明时候的类型
动态类型是指在运行时确定的类型
一个是编译时确定的,一个是运行时确定的。
- 动态绑定是说绑定对象的动态类型,静态绑定是指绑定对象的静态类型。
2. example
1.
#include <iostream>
using namesapce std;
public:
//Base();
void f0()
{
cout<<"Base::f0()"<<endl;
}
virtual void f1()
{
cout<<"Base::f1()"<<endl;
}
};
class Child1: public Base{
public:
void f0()
{
cout<<"Child1::f0()"<<endl;
}
void f1()
{
cout<<"Child1::f1()"<<endl;
}
};
class Child2: public Base{
public:
void f0()
{
cout<<"Child2::f0()"<<endl;
}
void f1()
{
cout<<"Child2::f1()"<<endl;
}
};
int main(){
Base* A = new Base();
Child1* B = new Child1();
Child2* C = new Child2();
A->f0();
A->f1(); // Base::f1()
B->f0();
B->f1(); // Child1::f1()
C->f0();
C->f1(); // Child2::f1()
A = B; // 动态绑定 B
A->f0(); // ? Base::f0()
A->f1(); // Child1::f1();
A = C;
A->f0(); // ? Base::f0()
A->f1(); // Child2::f1();
A = NULL;
A->f0(); // Base::f0()
A->f1(); // 编译不报错,运行报错,由于是动态类型绑定?
return 0;
}