什么是C++中的早期(静态)和后期(动态)绑定?

Sla*_*zer 24 c++

早期和晚期绑定在C++中是如何形成的?你举个例子吗?

我读到函数重载是早期绑定,虚函数是后期绑定.我读到 "早期(或静态)绑定是指编译时绑定,而后期(或动态)绑定是指运行时绑定".

Mat*_* M. 24

你看对了.基本示例可以给出:

using FuncType = int(*)(int,int); // pointer to a function
                                  // taking 2 ints and returning one.

int add(int a, int b) { return a + b; }
int substract(int a, int b) { return a - b; }
Run Code Online (Sandbox Code Playgroud)

静态绑定是在编译时已知绑定:

int main() {
    std::cout << add(4, 5) << "\n";
}
Run Code Online (Sandbox Code Playgroud)

没有动态改变操作的空间,因此是静态约束的.

int main() {
    char op = 0;
    std::cin >> op;

    FuncType const function = op == '+' ? &add : &substract;

    std::cout << function(4, 5) << "\n";
}
Run Code Online (Sandbox Code Playgroud)

而在这里,根据输入,一个得到9或-1.这是动态绑定的.

此外,在面向对象的语言中,virtual函数可用于动态绑定某些东西.因此,一个更详细的例子可能是:

struct Function {
    virtual ~Function() {}
    virtual int doit(int, int) const = 0;
};
struct Add: Function {
    virtual int doit(int a, int b) const override { return a + b; } 
};
struct Substract: Function {
    virtual int doit(int a, int b) const override { return a - b; } 
};

int main() {
    char op = 0;
    std::cin >> op;

    std::unique_ptr<Function> func =
        op == '+' ? std::unique_ptr<Function>{new Add{}}
                  : std::unique_ptr<Function>{new Substract{}};

    std::cout << func->doit(4, 5) << "\n";
}
Run Code Online (Sandbox Code Playgroud)

它在语义上等同于前面的例子......但是引入了virtual函数的后期绑定,这在面向对象的编程中很常见.

  • @NikosC.:我已经添加了虚拟方法; 我不太愿意添加vtable/v-ptr以回应看起来像初学者的问题.它可能有点太深入了. (3认同)

duf*_*ymo 5

这些都适用于所有面向对象的语言,而不仅仅是C++.

静态,编译时绑定很容易.没有涉及多态性.在编写和编译并运行代码时,您知道对象的类型.有时狗只是一只狗.

动态,运行时绑定是多态性的来源.

如果在编译类型中有一个父类型的引用,则可以在运行时为其指定子类型.引用的行为将在运行时神奇地更改为适当的类型.将执行虚拟表查找以让运行时确定动态类型是什么.