C++:存在虚函数的父类和派生类的指针指向的内存探讨
本文讨论下面这种情况,指针指向的东西是啥:
(如果Base是父类,Derived是派生类,那么Base* (Derived)这种指针究竟指向了啥?
1.定义代码:
#include "iostream"
using namespace std;
class Base1{
public:
Base1():base1_1(11){
}
int base1_1;
virtual void base1_fun1(){
cout<<"base_fun1"<<endl;
}
};
class Base2{
public:
virtual void base2_fun1(){
cout<<"base2_fun1"<<endl;
}
};
class Base3{
public:
virtual void base3_fun1(){
cout<<"base_fun3"<<endl;
}
};
class Derived:public Base1,public Base2,public Base3{
public:
virtual void derived_fun1(){
cout<<"derived_fun1"<<endl;
}
virtual void base1_fun1(){
cout<<"derived_fun1"<<endl;
}
};
2.main代码:
int main(){
Derived d1;
Base1* ptr1 = &d1;
Base2* ptr2 = &d1;
Base3* ptr3 = &d1;
Derived* ptr4 = &d1;
ptr1->base1_fun1();//1
ptr3->base3_fun1();
ptr4->base1_fun1();
ptr4->base3_fun1();
ptr4->derived_fun1();
cout<<&d1<<" ";
cout<<ptr1<<" ";
cout<<ptr2<<" ";
cout<<ptr3<<" ";
cout<<ptr4<<" ";
cout<<endl;
}
3.结果
4.结论
Derived d1;
Base1* ptr1 = &d1;
Base2* ptr2 = &d1;
Base3* ptr3 = &d1;
Derived* ptr4 = &d1;
我觉得种种迹象表明
Base1指针指向派生类d1的话,实际上是只会看到Base1的虚函数,也只会看到Base1的构造函数出来的东西。
Derived指针的话,啥都能看到。