2011-05-03 3 views
3

C++에서 : 가상 기능을 덮어 쓰지 않고 가상 기능을 덮어 쓰는 것과 다른 점은 무엇입니까? virtual 함께비 가상 함수 및 가상을 덮어 쓰는 것과 다른 점은 무엇입니까?

+2

덮어 쓰기는 아무런 의미가 없습니다. 멤버 함수 숨기기, 재정의 또는 오버로드에 대해 묻고 싶습니까? 질문을 명확히하려면 여기에서 각각 검색하십시오. –

+0

아무도 언급하지 않는 경우 : [The Definitive C++ Book Guide and List] (http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)를 참조하여 직접 구매하십시오. C++에 대한 좋은 책. –

답변

8

:

class Base { 
    virtual void Foo() { std::cout << "Foo in Base" << std::endl;} 
}; 

class Derived : public Base { 
    virtual void Foo() { std::cout << "Foo in Derived" << std::endl;} 
}; 

// in main() 
Derived* d = new Derived(); 
d->Foo(); // prints "Foo in Derived" 

Base* b = new Derived(); 
b->Foo(); // prints "Foo in Derived" 

와없이

(동일한 코드 있지만 아웃 떠나 virtual)

// in main() 
Derived* d = new Derived(); 
d->Foo(); // prints "Foo in Derived" 

Base* b = new Derived(); 
b->Foo(); // prints "Foo in Base" 

그래서 차이 virtual없이 진정한 런타임 다형성 없다이다 : 어떤 함수가 호출되는 포인터/참조의 현재 유형에 따라 컴파일러에 의해 결정됩니다. 런타임에, 당신은 그것의 가상 멤버 호출 할 때마다 - virtual

, 객체가되는이 호출 할 함수의 실제 주소를 보이는 가상 함수 ( vtable)의 목록을 유지 관리합니다. 이 샘플에서는 Foo에 대한 항목이 Derived 생성자에 의해 겹쳐 쓰여진 함수를 가리 키도록 암시 적으로 수정되므로 -pointer를 통해 Foo이 호출되는 것이 중요하지 않습니다.

0

가상 함수를 덮어 쓰면 런타임에 개체 유형이 평가되고 적절한 방법이 호출됩니다.

예 :

class Vehicle 
{ 
public: 
    void PrintType(); // Prints "Vehicle" 
}; 

class Car: public Vehicle 
{ 
// overwrite PrintType to print "Car" 
}; 


// In main 
void main() 
{ 
Vehicle *s = new Car(); 
s->PrintType(); // Prints "Vehicle" 

// If PrintType was virtual then the type of s will be evaluated at runtime and the inherited function will be called printing "Car" 
} 
관련 문제