在对象继承中构造对象后设置以后的值

时间:2013-05-08 14:21:06

标签: c++ object inheritance polymorphism

Shape *shape[100];
Square sqr;

void inputdata() {
int len,width;
cout << "enter length";
cin >> len;
cout << "enter width";
cin >> width;

sqr = Square(len,width,0); //---> i have not compute area for this, i just put a 0 for it first     
shape[0] = &sqr;
}

void computeArea() {
int area;
area = shape[0]->computeArea();
//----> need to set my area here after getting it
}

shape是父类,square是子类

创建方形对象并将其插入形状数组后。我无法到达方形类中的setArea()方法来设置区域。

我已经找到了两个解决方案,但觉得它不适合对象继承多态。

一种方法是在形状类中实现setArea()(我已经在方形类上使用setArea())并通过多态来调用setArea方法并将其设置为我的方形区域属性。

另一种方法是在shape类中创建一个get对象方法,它是getSquare()所以我可以通过Shape数组到达getArea()方法

我的两种方法有效吗?或者有更好的方法吗?

class Square: public Shape{

private:
int len;
int width;
int area;

public:
Square(string,int,int,int);
int getArea();
void setArea(int);
};

int Square::computeArea() {
int sqrArea = len*width;
area = setArea(sqrArea);
return sqrArea;
}

int Square::setArea(int _area) {
area = _area;
}

3 个答案:

答案 0 :(得分:1)

计算区域应该是所有形状的共同点,因此将computeArea提升到基类(并且可能使其成为抽象)似乎是一种有效的解决方案。

答案 1 :(得分:0)

如果你的Square真的依赖于通过某人传递自己computeArea()的结果来设置其区域,那么你的设计看起来就错了。

为什么不实现computeArea()以便它在对象上设置区域并返回它?

修改

根据您更新的问题,为什么SetArea()会返回任何内容?实际上,根据声明,它没有,但它的定义确实如此。简单地完全放弃SetArea()(无论如何,从外面设置一个正方形区域有什么意义?)并执行此操作:

class Square: public Shape {

private:
  int len;
  int width;
  int area;

public:
  Square(string,int,int,int);
  int getArea();
};

int Square::computeArea() {
  area = len*width;
  return area;
}

答案 2 :(得分:0)

如果你真的只想在setArea课程中实施Square,你可以dynamic_cast

if ( Square *s = dynamic_cast<Square *>shape[0] ) {
  s -> setArea();
}

通常使用dynamic_cast是设计不良的标志,在这种情况下,为什么不Shape实施setArea(),因为区域对于所有形状都是通用的。