C++方法继承帮助
我有一个 Graphic
类,用于处理 Item
的绘制,因此我的所有 Item
类都将继承它。
本质上,我有一个 Graphic::Draw(type argX, type argY)
方法,需要将 argX
和 argY
传递给它通过 Item
方法。
所以我想我可以很容易地拥有一个像这样的 Item::DrawMe()
方法:
class Graphic {
...
void Draw(type argX, type argY)
{
// drawing code
}
...
}
class Item : public Graphic {
...
type mX;
type mY;
...
void DrawMe() : Draw(this->mX, this->mY) { }
...
};
但我宁愿有名为 Item 的
Item::DrawMe()
方法: :Draw() 代替。但是,Item::Draw()
方法将与 Graphic::Draw
方法具有相同的名称。但我不能使用 virtual
基方法,因为我显然不想覆盖函数体......
那么我应该怎么做呢?谢谢。
I have a Graphic
class that handles the drawing of an Item
, and so all of my Item
classes will inherit it.
In essence, I have a Graphic::Draw(type argX, type argY)
method, that requires argX
and argY
to be passed to it by the Item
method.
So think I could easily have an Item::DrawMe()
method like this:
class Graphic {
...
void Draw(type argX, type argY)
{
// drawing code
}
...
}
class Item : public Graphic {
...
type mX;
type mY;
...
void DrawMe() : Draw(this->mX, this->mY) { }
...
};
But I would rather have the Item::DrawMe()
method named Item::Draw()
instead. However, then the Item::Draw()
method would then have the same name as the Graphic::Draw
method. But I can't use a virtual
base method, because I don't want to overwrite the body of the function obviously...
So how should I do this? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以只限制子级 Draw 调用的范围,以显式调用 Graphic::Draw(type,type)。 .. 例如:
但要注意 Item::Draw(void) 阴影(隐藏)Item::Draw(type,type)。您不会在子类中看到这两个重载(例如 Item 对象)。您必须使用显式范围...(例如ItemObject->Graphic::Draw(x,y)。)或者可能“使用“子句...
另外,您会遇到与多态性有关的编码复杂性...通过单个虚拟 Draw() 引用一组Graphic对象是很好的选择方法。例如:项目 i;图形*g=&我; g->draw(foo,bar);
我的建议是:
当然,你最好迁移 type mX 和 type mY 进入基类开始...大概大多数图形对象都会有一个x,y< /strong> 位置...
You could just scope the child's invocation of Draw to call Graphic::Draw(type,type) explicitly... E.g.:
But watch out for Item::Draw(void) shadowing (hiding) Item::Draw(type,type). You won't see both overloads in the child class (e.g. Item objects). You'd have to use explicit scoping... (Like ItemObject->Graphic::Draw(x,y).) Or possibly a "using" clause...
Also, you run into coding complexities with respect to polymorphism... It's nice to refer to a set of Graphic objects via a single virtual Draw() method. E.g.: Item i; Graphic * g = & i; g->draw(foo,bar);
What I would suggest would be something along the lines of:
Of course, you'd be better off migrating type mX and type mY into the base class to begin with... Presumably most Graphic objects will have an x,y location...
没有办法解决这个问题,因为您需要为每个子
Draw
提供不同的功能,如果您不能使用virtual
那么您必须为父函数和子函数选择不同的名称。只需将父函数命名为DoDraw
并将子函数命名为Draw
即可。No way around it since you need different functionality for each child
Draw
, if you can't usevirtual
then you'll have to pick separate names for the parent and child functions. Just name the parent functionDoDraw
and the childDraw
.