gpt4 book ai didi

c++ - 对象类型如何在编译时未知?

转载 作者:行者123 更新时间:2023-11-30 04:15:20 25 4
gpt4 key购买 nike

我目前正在学习动态绑定(bind)和虚函数。这是来自 Accelerated C++,第 13 章:

[...] We want to make that decision at run time. That is, we want the system to run the right function based on the actual type of the objects passed to the function, which is known only at run time.

我不明白对象的类型在编译时是未知的这个想法。从源码上看不是很明显吗?

最佳答案

完全没有。考虑这个例子:

struct A {
virtual void f() = 0;
};

struct B : A {
virtual void f() { std::cerr << "In B::f()\n"; }
};

struct C : A {
virtual void f() { std::cerr << "In C::f()\n"; }
};

static void f(A &a)
{
a.f(); // How do we know which function to call at compile time?
}

int main(int,char**)
{
B b;
C c;
f(b);
f(c);
}

编译全局函数f 时,无法知道它应该调用哪个函数。事实上,每次都需要调用不同的函数。第一次用f(b)调用,需要调用B::f(),第二次用f调用(c) 它需要调用 C::f()

关于c++ - 对象类型如何在编译时未知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18394106/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com