【发布时间】:2013-05-02 19:54:38
【问题描述】:
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 是子类
创建方形对象并将其插入形状数组后。我无法在我的 square 类中使用 setArea() 方法来设置区域。
我已经找到了两种解决方案,但是感觉它不适合对象继承多态。
一种方法是在 shape 类中实现 setArea()(我已经在 square 类上设置了 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;
}
【问题讨论】:
-
显示 Square 和 Shape 类!
-
你在
inputdata()方法上有一个错误,你应该使用sqr = new Square(len, width, 0),看看你的编译器产生的警告,它们在这里不仅是为了惹恼你。言归正传,给我们解释一下,为什么需要将Squares 保留在Shape类型的数组中。如果你想对这个数组使用Square-specific 方法,你可以使用Square *square[100];数组。如果您想在其中保留其他对象,为什么要使用仅对Squares 可用的方法?看起来像是设计问题,请为我们提供Square和Shape类,以便我们为您提供帮助。
标签: c++ object inheritance polymorphism