《VC++深入详解》第三章74页的问题(孙鑫老师)

就《VC++深入详解》第三章74页的内容,视频中,孙鑫老师讲到(大意是),创建派生类对象的时候,基类构造函数中this是指的谁呢?是指的派生类对象!
对此,胡乱写了个程序如下:(其中利用了虚函数的技术 )


#include <iostream>
using namespace std;

class base
{
public:
 int i;
 
 base();
 //~base();
 virtual void show() { cout << "this is base class show() /n";}
};
class derived : public base
{
public:
 int i;
 derived() ;
 //~derived();
 virtual void show() { cout << "this is derived class show() /n";}
};


base *p;

base::base()

 cout << "in base /n";
 p=this;
 this->show();
 p->show();
};

derived::derived()   : base()
{  
 cout << "in derived /n";
 this->show();
 p->show();
};


derived od;

int _tmain(int argc, _TCHAR* argv[])
{
 cout << "in main() /n";
 od.show();
 p->show();
 ((derived *) p)->show(); //当不使用虚函数的时候,用来说明“强制”的转换 。sorry习惯了C的写法了。

 //一个问题:这里可以(reinterpret_cast<derived *>(p))->show();吗? 试一试吧!
 system("pause");
 return 0;
}

执行结果是:

in base
this is base class show()
this is base class show()
in derived
this is derived class show()
this is derived class show()
in main()
this is derived class show()
this is derived class show()
this is derived class show()
请按任意键继续. . .

当去掉base基类的virtual关键字的时候执行结果变成了:

in base
this is base class show()
this is base class show()
in derived
this is derived class show()
this is base class show()
in main()
this is derived class show()
this is base class show()
this is derived class show()
请按任意键继续. . .

 

 

事情是否就清楚了呢?是否就佐证了基类对象的this指针,指示的是派生类了呢?

 

下面的例子:

#include <iostream>
using namespace std;
int base_size,derive_dsize;
class base
{
public:
 int i; 
 base(int);

};
class derived : public base
{
public:
 int i,j;
 derived(int,int,int) ;
};


base::base(int a=1)

 base_size = sizeof(*this);
 cout << "in base /n";
};

derived::derived(int a=1,int b=2,int c=3)   : base(a)
{  
 i=b;
 j=c;
 derive_dsize = sizeof(*this);
 cout << "in derived /n";
};


derived oa ;

int main( )


 cout<< "/nBase   size : " << sizeof(base) << "/n"; 
 cout<< "/nDerive size : " << sizeof(derived) << "/n/n";

 cout<< "/nBase   size : " <<  base_size << "/n"; 
 cout<< "/nDerive size : " <<  derive_dsize << "/n/n";
 system("pause");
 return 0;
}

执行结果是:

in base
in derived

Base   size : 4

Derive size : 12


Base   size : 4

Derive size : 12

请按任意键继续. . .

 

基类的成员函数中的this指针,指示的是这个基类产生对象。不是指示的这个基类的派生类对象。基类中成员函数中的this指针,与派生类的this指针,虽然它们的地址是相同的、虽然通过虚函数技术可以用基类指针,来调用派生类的函数(可以调用派生类的私有函数吗?私有变量也可以访问吗?如果觉得好玩,一试便知!)、虽然也可以利用强制的类型转换,使得基类指针它成为派生类对象的指针。但实质上,二者的类型是不同。

this指针的设计是为了(一份)成员函数,确能处理多个由这个类生产出来的对象而设计的。

 

 

posted on 2009-08-26 10:48  johnphan  阅读(103)  评论(0编辑  收藏  举报

导航