首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

碰到一个有关问题

2012-02-17 
碰到一个问题,请教高手代码://aa.cpp:Definestheentrypointfortheconsoleapplication.//#includestdafx.h

碰到一个问题,请教高手
代码:

//   aa.cpp   :   Defines   the   entry   point   for   the   console   application.
//

#include   "stdafx.h "
#include   <vector>

using   namespace   std;


class   Widget
{
public:
Widget()
{
cout   < <   "Widget()   is   called!\n ";
}

virtual   ~Widget()
{
cout   < <   "~Widget()   is   called!\n ";
}

virtual   void   Output()
{
cout   < <   "Widget   Output   is   called!\n ";
}

private:

};

class   SpecialWidget   :   public   Widget
{
public:
SpecialWidget()
{
cout   < <   "SpecialWidget()   is   called!\n ";
}

~SpecialWidget()
{
cout   < <   "~SpecialWidget()   is   called!\n ";
}

void   Output()
{
cout   < <   "SpecialWidget   Output   is   called!\n ";
}

void   test()
{
cout   < <   "SpecialWidget   test   is   called!\n ";
}

private:

};

int   _tmain(int   argc,   _TCHAR*   argv[])
{
Widget*   pw   =   new   SpecialWidget;
pw-> Output();

SpecialWidget*   spw   =   static_cast <SpecialWidget*> (   new   Widget   );
spw-> Output();
spw-> test();

return   0;
}

输出:
Widget()   is   called!
SpecialWidget()   is   called!
SpecialWidget   Output   is   called!
Widget()   is   called!
Widget   Output   is   called!
SpecialWidget   test   is   called!

问题:为什么test()函数能够被调用?

c++帮助文件中关于static_cast的解释:

For   example:

class   B   {   ...   };

class   D   :   public   B   {   ...   };

void   f(B*   pb,   D*   pd)
{
        D*   pd2   =   static_cast <D*> (pb);                 //   not   safe,   pb   may
                                                                                  //   point   to   just   B

        B*   pb2   =   static_cast <B*> (pd);                 //   safe   conversion
        ...
}
In   contrast   to   dynamic_cast,   no   run-time   check   is   made   on   the   static_cast   conversion   of   pb.   The   object   pointed   to   by   pb   may   not   be   an   object   of   type   D,   in   which   case   the   use   of   *pd2   could   be   disastrous.   For   instance,   calling   a   function   that   is   a   member   of   the   D   class,   but   not   the   B   class,   could   result   in   an   access   violation.



希望高手能回答一下上面的问题?

[解决办法]
spw既指向Widegt,也指向SpecialWidget,Widget是SpecialWidget的一个部分,明白了么?
[解决办法]
成员函数和普通函数一样,只是多了一个 this 指针参数,你指向的对象不对,只是 this 指针这个参数是错误的,但是你的函数里没有访问任何类的成员变量,也就是没有用到 this 指针这个参数。所以虽然这个参数是错误的,但没用到也不会报错。
[解决办法]
SpecialWidget* spw = NULL;
spw-> test();
这样也都不会出错,因为你根本没有访问子类特有的成员变量。
成员函数说白了也是一个地址,非虚的成员函数地址是固定的,当然可以用spw-> test()调用,调用普通成员函数的时候会有一个默认参数const classtype* this,如果spw是NULL的时候调用,那么只是这个this的值为NULL而已,只要你不用“this-> 成员变量”去访问,就不会有问题。

[解决办法]
指针的类型和指针指向的实际对象可以不一致的。
static_cast 之后,指针指向的对象还是 widget. 但是指针的类型是 SpecialWidget*, 只要你愿意,你可以让 SpecialWidget* 的指针指向任何内容。

热点排行