您的位置:首页 > 编程语言 > C语言/C++

C++的静态绑定与动态绑定

2010-09-26 10:08 267 查看
C++语言默认采用的是静态绑定。

class Person {
public:
void func() {
printf("AAAAAAAAAAAA/n");
}
};

class Child : public Person
{
public :
void func() {
printf("BBBBBBBBBBBB/n");
}
};

int main()
{
Child child;
Person person = child;
Person *ptr = &child;
person.func();
ptr->func();
return 0;

}

上述打印的结果:
AAAAAAAAAAAA
AAAAAAAAAAAA
因为动态绑定的执行效率更低,c++默认采用静态绑定。如果需要动态绑定,则需要特别声明,采用virtual标识。
1. 静态绑定:根据编译时申明的变量类型,来决定调用的是哪个类型的函数;
2. 动态绑定:根据运行时实际赋给变量的类型,来决定调用的是父类或子类的函数。

如果将Person类的func函数加上virtual修饰,让其成为虚函数。

class Person {
public:
virtual void func() {
printf("AAAAAAAAAAAA/n");
}
};

上述打印的结果:
AAAAAAAAAAAA
BBBBBBBBBBBB

只有通过指针或引用来访问对象的虚函数时,才能够进行动态绑定。
故上述的
Person person = child;
person.func();
调用的函数还是Person类的func,因为没有动态绑定。

--------------------------------------------
再举一例
#include <iostream>
#include <stdlib.h>

using namespace std;

class CBase
{
public:
virtual int func() const    //虚函数
{
cout<<"CBase function! "<<endl;
return 100;
}
};

class CDerive : public CBase
{
public:
int func() const        //在派生类中重新定义虚函数
{
cout<<"CDerive function! "<<endl;
return 200;
}
};

int main()
{
CDerive obj1;
CBase* p1 = &obj1;
CBase& p2 = obj1;
CBase p3 = obj1;
CBase obj2;

obj1.func();    //静态绑定:调用对象本身(派生类CDerive对象)的 func 函数
p1->func();    //动态绑定:调用被引用对象所属类(派生类CDerive)的 func 函数
p2.func();      //动态绑定:调用被引用对象所属类(派生类CDerive)的 func 函数
p3.func();       //静态绑定:调用对象本身(基类CBase对象)的函数
obj2.func();    //静态绑定:调用对象本身(基类CBase对象)的函数
return 0;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: