#include <iostream>
using namespace std;
class Base{
public:
virtual void f(float x){cout<<"Base::f(float)"<<x<<endl;}
void g(float x){cout<<"Base::g(float)"<<x<<endl;}
void h(float x){cout<<"Base::h(float)"<<x<<endl;}
};
class Derived:public Base{
public:
virtual void f(float x){cout<<"Derived::f(float)"<<x<<endl;}
void g(int x){cout<<"Derived::g(int)"<<x<<endl;}
void h(float x){cout<<"Derived::h(float)"<<x<<endl;}
};
int main(void){
Derived d;
Base *pb=&d;
Derived *pd=&d;
//Good:behavior depends solely on type of the object
pb->f(3.14f); //Derived::f(float)3.14
pd->f(3.14f); //Derived::f(float)3.14
//Bad:behavior depends on type of the pointer
pb->g(3.14f); //Base::g(float)3.14
pd->g(3.14f); //Derived::g(int)3(surprise!)
//Bad:behavior depends on type of the pointer
pb->h(3.14f); //Base::h(float)3.14(surprise!)
pd->h(3.14f); //Derived::h(float)3.14
return 0;
}
공부 가상 함수 후, 나는 내가 어떻게 형체 작업 아이디어를 가지고 생각하지만, 여전히 몇 가지가 있습니다 : 나는 C++에서 다형성을 연구 할 때
, 나는 여기에 작은 예를 찾을 수 이 코드의 질문, 나는이 코드가 어떻게 작동하는지 설명하는 누군가를 귀찮게하지 않으려 고합니다. 파생 된 클래스 내에서 세부 정보를 표시 할 수있는 사람이 필요합니다 (너무 자세하게 설명 할 필요가 없으며, 메서드 포인터 Vtable과 그 구조는 가상 상속되지 않습니다.
pb-> h (3.14f); //Base::h(float)3.14 (깜짝!) 몇 가지 vtable이 있어야합니다. 맞습니까?
감사합니다.
자네 말이 맞아. 함수는'virtual'이어야하며, 이는 각 클래스 유형에 대한 vtable을 제공합니다. –
죄송합니다 드류, 내 가난한 영어입니다! 이 코드는 작동합니다. 파생 클래스 구조에 대한 내부 정보를 알고 싶습니다. – Kuan