this指针

孙鑫VC++教程,第三章中this指针

 

开始自己写错了,然后google得来一个此提问。

CTestAPP 由 CWinAPP 派生而来
CWinApp::CWinApp(LPCTSTR lpszAppName) //带参数
{
......
pThreadState->m_pCurrentWinThread = this;
//注意,这个this指针指向那个对象?是CWinAPP还是CTestAPP
//孙老师说是指向派生类CTestAPP的对象,但是我的试验中却是指向基类对象啊
ASSERT(AfxGetThread() == this);
......
}
我做的试验如下:
#include <iostream.h>

class Point
{
public:
void output()
{
cout<<"调用了基类的output()函数.";
}
void cjp()
{
this->output();
}
};

class test:public Point
{
public:
void output ()
{
cout<<"调用了派生类的output函数。";
}
};

void main()
{
test tt;
tt.cjp();
}

采纳答案:
----------------------------------
你所建的Test派生于父类Point,当VC在编译时,要确定每个对象调用的函数地址,即早期绑定,实际上在内存里tt是由父类Point和tt实际增加的内存部分组成,好比两块叠在一起的砖头,上面那块是父类Point,下面那块是tt,当你用tt调用cjp时,实际上已经静态联编了,即该对象是被认为是Point的对象所占的内存,当然会指向Point的Output.
那么这个时候就得调用虚函数,因为在你的派生类和子类里都有Point的函数,所以在Point类里面的Output前增加virtual即可.这样就实现了运行时的多态.



--------------------------------------
没懂你的意思,不过你的程序里面派生类没有重写cjp函数,你调用的当然是基类中的cjp函数了,如果你想实现多态,要在基类中将cjp定义成虚函数,派生类里面再改写该函数,然后就可以用基类的指针指向派生类对象,实现派生类函数的调用了。



--------------------------------------------
基类的 output 函数没有定义为 virtual,派生类不是重写而是又定义了一个 output。
在基类的 void output() 前面加上 virtual 就可以了。




然后自己又写代码加深理解
 1 #include "stdafx.h"
 2 struct member
 3 {
 4     member()
 5     {    
 6         printf("member ctor\n");
 7     }    
 8 };
 9 class Parent
10 {
11 public:
12     Parent()
13     {
14         printf("parent ctor\n");
15         p =this;
16     }
17 
18     virtual void education()
19     {
20         printf("parent education\n");
21     }
22     static Parent * p;
23     static member m;
24 };
25 
26 class Children: public Parent
27 {
28 public:
29     Children()
30     {
31         printf("children ctor\n");
32     }
33     void education()
34     {
35         printf("children learn");
36     }
37 };
38 
39 
40 Parent * Parent::p = NULL;
41 Children c;
42 member mem;
43 member Parent::m = member();
44 int _tmain(int argc, _TCHAR* argv[])
45 {    
46     printf("main\n");
47     
48     Parent::p->education();
49     getchar();
50     return 0;
51 }
View Code

 


1 类的静态成员变量 与 类的实例对象 没有关系 (后面查找类和静态成员的关系?)
2 不加virtual最后一行输出 parent education ,加上virtual最后一行输出 children learn (后面查找虚函数表?)

posted @ 2014-03-09 00:50  kira2will  阅读(406)  评论(0编辑  收藏  举报