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

setting a later value after constructing an object in object inheritance

本文关键字:对象 设置 继承      更新时间:2023-10-16
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()方法来设置区域。

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

一种方法是在shape类中实现setArea()(我已经在square类中有setArea()),并通过多态性调用setArea方法并将其设置为我的square area属性。

另一种方法是在shape类中创建一个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;
}

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

如果你真的只想在Square类中实现setArea,你可以dynamic_cast

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

通常使用dynamic_cast是一个糟糕的设计的标志,在这种情况下,为什么Shape不能实现setArea(),因为所有形状的面积都是通用的。

如果你的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;
}