在父类和子类中定义重载函数 心得

来源:互联网 发布:西安行知中学怎么分班 编辑:程序博客网 时间:2024/06/11 15:13

情景: 

今天碰到一个问题,父类A写了fun函数,自己重载了很多种形式,然后子类B写了一个fun函数进行重载,然后发现 子类对象访问不到父类的fun函数。直接使用代码说明情况

代码如下:

#pragma oncetypedef struct STRUCT_INT{int m_sTemp1;STRUCT_INT(){m_sTemp1=1;}}STRUCT_INT;typedef struct STRUCT_DOUBLE{double m_sTemp1;STRUCT_DOUBLE(){m_sTemp1=1.0;}}STRUCT_DOUBLE;typedef struct STRUCT_CHAR{char m_sTemp1;STRUCT_CHAR(){m_sTemp1='A';}}STRUCT_CHAR;class CA{public:CA(void);~CA(void);void fun(STRUCT_INT param1,STRUCT_INT param2);void fun(STRUCT_DOUBLE param1,STRUCT_DOUBLE param2);void fun(STRUCT_INT param1,STRUCT_DOUBLE param2);};

#pragma once#include "a.h"class CB :public CA{public:CB(void);~CB(void);void fun(STRUCT_CHAR param1,STRUCT_CHAR param2);};

 

剩下来就是使用类B了

CB *pClsB = new CB;STRUCT_DOUBLE temp1,temp2;pClsB->fun(temp1,temp2);STRUCT_INT temp3;pClsB->fun(temp3,temp2);STRUCT_CHAR temp4,temp5;pClsB->fun(temp4,temp5);delete pClsB;

直接提示:error C2664: 'CB::fun' : cannot convert parameter 1 from 'STRUCT_DOUBLE' to 'STRUCT_CHAR'

error C2664: 'CB::fun' : cannot convert parameter 1 from 'STRUCT_INT' to 'STRUCT_CHAR'

正确使用代码:

CB *pClsB = new CB;STRUCT_DOUBLE temp1,temp2;pClsB->CA::fun(temp1,temp2);STRUCT_INT temp3;pClsB->CA::fun(temp3,temp2);STRUCT_CHAR temp4,temp5;pClsB->fun(temp4,temp5);delete pClsB;

具体为什么明天解答。。。

2012年3月1日8:53

重载只是发生在类的内部,不会在父子之间传导,即便你有了virtual关键字那也是不好使的。子类写了和父类函数一样的函数 那就应该称为 覆盖。你如果真的想访问的话就应该将
进行强制类型转换或者类符限定。那么这个覆盖和具有virtual关键字的函数有什么差异呢?

我的理解是:

普通函数呢 就是普通函数没有什么动态连接的功能。而具有virtual关键字的函数是动态连接,此时就应该能引发多态。

结论:一旦子类覆盖父类的函数。你所需要的那部分函数都需要拿出来覆盖掉。具体形式你可以在子类里面调用父类的函数。

原创粉丝点击