在面向对象编程中,哪些函数调用在编译时没有被解析? [英] Which function calls are not resolved at compile time in object oriented programming?
问题描述
哪些函数调用在编译时解析,哪些在运行时解析?我在某处读到并非所有函数调用都在编译时解析,我不知道是哪个.
Which function calls are resolved at compile time and which ones at runtime? I read somewhere that not all function calls are resolved at compile time i dont know which.
推荐答案
虚拟函数调用机制在运行时解决.因为,在 C++ 中,指向派生类的指针与指向其基类的指针是类型兼容的.因此,要调用虚函数,必须知道基类指针所指向的构造对象(或实际下层对象)的实际类型,这只能在运行时解析.
Virtual function calling mechanisms are resolved at run-time. Because, in C++, a pointer to a derived class is type-compatible with a pointer to its base class. So, to call the virtual function, the actual type of constructed object( or the actual under lying object ) to which base class pointer is pointing to must be known, which can only be resolved at runtime.
struct foo
{
virtual void virtualMethod()
{
cout<< " \n virtualMethod of foo \n";
}
void normalMethod()
{
cout<< " \n normalMethod of foo \n";
}
virtual ~foo() {}
};
struct bar: public foo
{
void virtualMethod()
{
cout<< " \n virtualMethod of bar \n";
}
void normalMethod()
{
cout<< " \n normalMethod of bar \n";
}
~bar() {}
};
foo* obj = new bar ;
obj->virtualMethod() ;
现在,由于 virtualMethod()
需要调用哪个取决于运行时类型(或实际底层对象)obj
指向,因为 obj
可以指向由 new foo
或 new bar
构造的对象.在运行时,我们知道obj
是由一个返回类型为bar*
的对象构造的,如果存在,则调用派生类的相应虚函数.否则调用基类虚函数.
Now, since which virtualMethod()
needs to be called depends on the run time type( or the actual under lying object ) obj
is pointing to because obj
can be pointed to an object constructed by either new foo
or new bar
. At run-time, we know that that obj
is constructed from an objected whose type returned is bar*
, corresponding virtual function of the derived class is called, if exists. Else base class virtual function is called.
obj->normalMethod();
这个方法可以在编译时自己解析,因为它是一个普通的成员函数.
This method can be resolved at compile time itself because it's a normal member function.
结果:ideOne 结果链接
这篇关于在面向对象编程中,哪些函数调用在编译时没有被解析?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!