父类的this指针与子类的关系??代码写出来了希望分析下
学C++几天了,在一个视频中看到,说父类中出现的this指针,一旦有子类调用那么这个this指针就是指向派生类的,这句话我想了下大概明白,自己写了个例子不知道能不能支持这句话:
#include <iostream.h>class Father{public : Father(int i=0) { father=this;//保存this指针为public方便外部调用 cout<<this<<endl;//发现和Son构造函数的地址一致? } void Print() { cout<<"Father.Print"<<endl; } Father *father;};class Son:public Father{public: Son() { cout<<this<<endl; } void Print() { cout<<"Son.Print"<<endl; } };Son son;//实例化全局void main(){ Son *_son= (Son*)son.father;//获取这个this指针,强制转化 _son->Print();//看调用的是哪个,如果输出:Son.Print则保存的是派生类的this指针?}