[c++]父类数组直接调用方法,不会根据具体子类调用子类重写的方法,而是全部调用父类的方法【解决办法】

问题:例如:

父类:

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方法。

解决办法:

  1. 在父类里进行判断,直接写出所有子类的show的逻辑;
  2. 在这里进行强制类型转换,如下:
    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();
    		}
    	}

 总结:个人觉得从面向对象的角度来看,方法二应该更符合面向对象的方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿峰不想搬砖

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值