Pas*_*mer 2 c++ polymorphism binding runtime compile-time
如何确定以下调用是在编译时还是在运行时绑定?
object.member_fn;//object is either base class or derived class object
p->member_fn;//p is either base class or derived class pointer
Run Code Online (Sandbox Code Playgroud)
编辑:
#include <iostream>
using namespace std;
class Base
{
public:
Base(){ cout<<"Constructor: Base"<<endl;}
~Base(){ cout<<"Destructor : Base"<<endl;}
};
class Derived: public Base
{
//Doing a lot of jobs by extending the functionality
public:
Derived(){ cout<<"Constructor: Derived"<<endl;}
~Derived(){ cout<<"Destructor : Derived"<<endl;}
};
void foo()
{
Base & Var = Derived();
Base*pVar = new Derived;
delete pVar;
}
void main()
{
foo();
std::cin.get();
}
out put:
Constructor: Base
Constructor: Derived
Constructor: Base
Constructor: Derived
Destructor : Base // the Derived is not called,
// the PVal is of type Base* and the fn is not virtual
//so compile time binding
Destructor : Derived
Destructor : Base
Run Code Online (Sandbox Code Playgroud)
如果该方法不是虚拟的,则两个调用都将在编译时解析.如果该方法是虚拟的,那么您的question(obj.method())中的第一个调用将在编译时针对对象解析,但在运行时将用于引用.第二个call(objp->method())将在运行时解析.您还可以在编译时强制调用方法的非派生版本.
struct base {
void f();
virtual void v();
};
struct derived : public base {
void f();
void v(); // intentionally left virtual out, it does not really matter
};
int main() {
derived d;
base & b = d;
base * bp = &d;
// compile time:
d.f(); // derived::f
d.v(); // derived::v
b.f(); // base::f -- non-virtual
bp->f(); // base::f -- non-virtual
// runtime:
b.v(); // derived::v
bp->v(); // derived::v
// compile time (user forced):
b.base::v(); // base::v
bp->base::v(); // base::v
}
Run Code Online (Sandbox Code Playgroud)