<分区>
Possible Duplicate:
If virtual table is created in compile time, then why do we call this as a run time polymorphism?
我们说C++中虚函数的调用是在运行时决定的,而不是编译时决定的。所以我想我不清楚编译时和运行时的区别。在我粗略的想法中,一切都应该在编译时确定......谁可以帮助解决这个问题?谢谢!
标签 c++
<分区>
Possible Duplicate:
If virtual table is created in compile time, then why do we call this as a run time polymorphism?
我们说C++中虚函数的调用是在运行时决定的,而不是编译时决定的。所以我想我不清楚编译时和运行时的区别。在我粗略的想法中,一切都应该在编译时确定......谁可以帮助解决这个问题?谢谢!
最佳答案
看看这个简化的例子:
struct Base
{
virtual void func()
{ std::cout << "Base::func()" << std::endl; }
};
struct Derived : Base
{
virtual void func()
{ std::cout << "Derived::func()" << std::endl; }
};
有一个带有虚函数的基类,和一个覆盖它的派生类。现在这是我们的主要程序:
int main()
{
Base *bp = 0;
std::string input;
std::cin >> input;
if (input == "base")
bp = new Base;
else
bp = new Derived;
/* The compiler cannot decide which
function is called here: */
bp->func();
return 0;
}
编译器无法决定在 bp->func()
中调用基类的函数还是派生类的函数,因为它取决于来自用户的输入。
这说明了编译时和运行时之间的区别:编译器在编译时将您的代码转换为机器代码,但用户输入仅在运行时可用。
(我的代码示例不是完美的代码。例如,我声明了带有虚函数的类,但没有声明虚析构函数。还有其他问题。这只是为了说明编译时和运行时的区别,并每次都展示什么是可能的,什么是不可能的。)
关于c++ - 为什么说虚函数的调用不能在编译时确定呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14122528/