什么是C ++中的早期(静态)和晚期(动态)绑定? [英] What is early (static) and late (dynamic) binding in C++?

查看:110
本文介绍了什么是C ++中的早期(静态)和晚期(动态)绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

早期和晚期绑定在C ++中如何?你能举个例子吗?

How does early and late binding look like in C++? Can you give example?

我读的那个函数重载是早期绑定,虚函数是后期绑定。我阅读early(或static)绑定是指编译时绑定,后期(或动态)绑定是指运行时绑定。

I read that function overloading is early binding and virtual functions is late binding. I read that "early (or static) binding refers to compile time binding and late (or dynamic) binding refers to runtime binding".

推荐答案

您读得正确。基本示例可以使用:

You read right. The basic example can be given with:

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; }

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

Static binding is when binding is known at compile time:

int main() {
    std::cout << add(4, 5) << "\n";
}

不会为操作的动态更改留出空间,因此是静态绑定。

leaves no room for a dynamic change of the operation, and thus is statically bound.

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

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

    std::cout << function(4, 5) << "\n";
}

,而根据输入,可以得到9或-1。这是动态绑定。

whereas here, depending on the input, one gets either 9 or -1. This is dynamically bound.

此外,在面向对象语言中, virtual 函数可用于动态绑定某事。更详细的例子可以是:

Furthermore, in object oriented languages, virtual functions can be used to dynamically bind something. A more verbose example could thus be:

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";
}

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

which is semantically equivalent to the previous example... but introduces late binding by virtual function which is common in object-oriented programming.

这篇关于什么是C ++中的早期(静态)和晚期(动态)绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆