当基类被继承后this指针将代表派生类的this指针
2016-04-24 20:02
495 查看
假如有一派生类Derived,初始化时需要调用基类Base的构造函数,基类的构造函数中的this将代表派生类的this,但它的typeid还是基类。例如:
基类:
派生类:
main函数:
结果为:
可以看到,当派生类调用基类的构造函数时,this指针是派生类的this指针,typeid还是基类。
MFC就是这样获得当前WinApp对象指针的。如下:
结果:
基类:
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指针,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; }
结果:
相关文章推荐
- 学编程一定要上大学?美国一半码农都没有计算机学位
- IPerf——网络测试工具介绍与源码解析(2)
- 更改SQL Server 数据库的排序规则
- hdu2191 悼念512汶川大地震遇难同胞——珍惜现在,感恩生活 --多重背包
- Android ListView 侧滑效果实现(滑动展开、滑动删除)
- 码农小汪-解决java compiler level does not match the version of the installed java project facet
- java成神之路
- 20145211 《Java程序设计》第8周学习总结——自在飞花轻似梦
- 自白
- C++的4种类型转换关键字及其特点
- 共同学习Java源代码--常用工具类--AbstractStringBuilder(六)
- Using Database with Python -Basic Structured Query Language-Email Database Demo
- PHP 字符串处理
- 20145303 《Java程序设计》第8周学习总结
- 2016年3月14日作业
- SprimgMVC 三 :返回json形式数据
- php封装数据库mysql, mysqli
- sitemesh的使用
- bin和sbin的区别
- 单链表的排序(快排和冒泡实现)以及查找中间结点