아래의 호출이 컴파일 타임에 또는 런타임에 바인딩되는지 여부는 어떻게 결정됩니까?컴파일러에서 함수를 어떻게 해석합니까?
object.member_fn;//object is either base class or derived class object
p->member_fn;//p is either base class or derived class pointer
EDITED : 첫 번째 경우
#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
+1 예는 수천 단어에 해당합니다. –
+1,하지만 나는 암묵적으로 첫 번째 호출이 의미하는 바를 이해할 수 없습니다.이 호출은 두 번째 호출 집합과 세 번째 호출 집합에서 첫 번째 호출 집합으로 만들 수 있습니다. – yesraaj
당신이 말한 것들은 컴파일시에 컴파일되도록 실제로 최적화 될 수도 있습니다. 개체에 특정 클래스가 있어야 함을 증명할 충분한 정보와 충분한 지혜가 있다면 가상 호출을 비 가상으로 만들 수 있습니다. 그것들은 원칙적으로 런타임에 해결됩니다. –