问题描述
我正在做一个Shape类,它允许你获得某个形状的positionX,positionY和区域。派生类是一个Circle,它有一个附加的半径变量。
I'm doing a Shape class that allows you to get the positionX, positionY, and area of some shape. The derived class is a Circle, which has an added variable of radius.
class Shape
{
public:
Shape( double positionX, double positionY );
virtual double getPositionX() = 0;
virtual double getPositionY() = 0;
virtual double area() = 0;
class Circle : public Shape
{
public:
Circle( double positionX, double positionY, double radius );
virtual double getPositionX();
virtual double getPositionY();
virtual double area();
virtual double getRadius();
在我的主要内容中,我有一个Shapes数组,第一个对象是一个新的Circle并且正在调用这个圈子上的方法。
In my main, I have an array of Shapes with the first object being a new Circle and am calling methods on this Circle.
int main()
{
Shape* s[2];
s[0] = new Circle( 2.0, 3.0, 4.0 );
cout << s[0]->getPositionX() << endl; // Works fine.
cout << s[0]->getPositionY() << endl; // Works fine.
cout << s[0]->getRadius() << endl; // Doesn't work because s is a shape and my shape class has
// no getRadius() method.
如何调用getRadius()方法?
How do I call the getRadius() method?
推荐答案
Ug ......一个好的设计完全避免了这一点。如果你需要得到某个东西的半径,那么最好是能够提供半径的东西。如果形状是三角形,你的程序应该做什么?
Ug...A good design avoids this entirely. If you need to get the radius of something, then it better be something that can provide a radius. If the shape was a triangle, what should your program do?
现在解决这个问题的方法是使用动态强制转换:
Now the way around this is to use dynamic cast:
Circle* circ = dynamic_cast<Circle*>(s[0]);
if (circ)//check if cast succeeded
{
cout << circ->getRadius() << endl;
}
但这段代码闻起来。一般来说,如果你必须使用dynamic_cast(这很慢而且很混乱)那么你应该重新考虑你的设计。
But this code smells. In general, if you have to use dynamic_cast (which is slow and messy) then you should be rethinking your design.
这篇关于使用不在基类中的派生方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!