假如有一派生类Derived,初始化时需要调用基类Base的构造函数,基类的构造函数中的this将代表派生类的this,但它的typeid还是基类。例如:

基类:

class Base{
public:
Base()
{
cout << "Base this : " << typeid(this).name() << endl;
cout << "Base this =" << this << endl;
}
void fun()
{
cout << "fun this : " << typeid(this).name() << endl;
cout << "fun this =" << this << endl;
}
};

派生类:

class Derived : public Base{
public:
Derived(){
cout << "Derived this : " << typeid(this).name() << endl;
cout << "Derived this = " << this << endl;
}
};

main函数:

int main(int argc, char* argv[])
{
std::cout << "*****************Derived**********************\n";
Derived dev;
dev.fun();
std::cout << "\n*****************Base**********************\n";
Base base;
base.fun();
system("pause");
return 0;
}

结果为:
当基类被继承后this指针将代表派生类的this指针_虚函数
可以看到,当派生类调用基类的构造函数时,this指针是派生类的this指针,typeid还是基类。

MFC就是这样获得当前WinApp对象指针的。如下:

#include <iostream>
using namespace std;

class CWinApp;
CWinApp *m_pCurrentWinApp;

class CWinApp{
public:

CWinApp()
{
cout << "CWinApp this : " << typeid(this).name() << endl;
cout << "CWinApp this =" << this << endl;
m_pCurrentWinApp = this;
cout << endl;
}
virtual void fun()
{
cout << "CWinApp fun this : " << typeid(this).name() << endl;
cout << "CWinApp fun this =" << this << endl;
cout << endl;
}
};

class CMyWinApp : public CWinApp{
public:
CMyWinApp() {
cout << "CMyWinApp this : " << typeid(this).name() << endl;
cout << "CMyWinApp this = " << this << endl;
cout << endl;
}

virtual void fun()
{
cout << "CMyWinApp fun this : " << typeid(this).name() << endl;
cout << "CMyWinApp fun this =" << this << endl;
cout << endl;
}
};

/*这是个全局变量,因此会调用CMyWinApp构造函数,由于基类为CWinApp,所以先调用CWinApp构造函数,
这样,通过m_pCurrentWinApp = this,m_pCurrentWinApp就指向了CMyWinApp对象。
(也就是说,m_pCurrentWinApp是一个基类指针,指向派生类对象,调用虚函数时,就会调用派生类的对应虚函数。)*/
CMyWinApp theApp;

int main()
{
std::cout << "m_pCurrentWinApp=" << m_pCurrentWinApp << endl;;
m_pCurrentWinApp->fun();

system("pause");
return 0;
}

结果:
当基类被继承后this指针将代表派生类的this指针_构造函数_02