问题:例如:
父类:
class CtlBase
{
public:
char content[30];
int ctlType;
CtlBase();
CtlBase(int x,int y,int w,int h,char *content,int ctlType);
~CtlBase();
void show();
private:
int x;
int y;
int w;
int h;
};
子类1:
class Label:public CtlBase
{
public :
Label();
Label(int x,int y,int width,int height,char *content,int ctlType);
private:
};
子类2:
class Edit:public CtlBase
{
public :
int ips;
int length;//最大长度
int type;//允许输入的类型:1.数字,2.字母,3.字母或数字
Edit();
Edit(int x,int y,int width,int height,char *content);
Edit(int x,int y,int width,int height,char *content,int ips,int length,int type,int ctlType);
void editKeyListen(int ch);
void show();
};
对于以下代码段:
CtlBase *ctls[30];
for(int i = 0;i<this->count;i++)
this->ctls[i]->show();
ctls是一个含有不同子类的父类指针数组,父类有一个show方法,每个子类也都重写一个show方法。但是上述语句进行调用的时候,所有的show方法走的都是父类的show方法。
解决办法:
- 在父类里进行判断,直接写出所有子类的show的逻辑;
- 在这里进行强制类型转换,如下:
for(int i = 0;i<this->count;i++) { if(this->ctls[i]->ctlType == LABEL) { this->ctls[i]->show(); } else if(this->ctls[i]->ctlType == EDIT) { static_cast<Edit*>(this->ctls[i])->show(); } else if(this->ctls[i]->ctlType == BUTTON) { static_cast<Button*>(this->ctls[i])->show(); } }
总结:个人觉得从面向对象的角度来看,方法二应该更符合面向对象的方法。