在对象继承中构造对象后设置稍后的值
setting a later value after constructing an object in object inheritance
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;
}
相关文章:
- 如何在自删除后将对象设置为nullptr
- 在 c++ 中将对象设置为等于同一类的构造函数是否有效?
- std::用派生类对象设置,但用gcc8.1设置基类比较器
- 如何在 gdb 中的所有构造函数上同时为 C++ 对象设置断点?
- 如何将C++ time_t对象设置为纪元?
- 使用PYBIND11,如何为Array_t对象设置基础内存的所有权
- 如何使用基类对象设置派生类变量的值
- C 不能将对象设置为方法的返回对象
- 一旦对象设置为 null,用于声明对象的堆大小的变量就设置为 null?
- 无法在openGL和GLUT中为我想要的确切对象设置动画
- 如何将2D向量中的对象设置为空指针[C ]
- 如何用类别的consumetrized构造函数声明使用类的比较对象设置的STL设置
- 为什么重载运算符不将主对象设置为值集
- 如何在 OpenGL 中为 3D 对象设置原点
- C++是否可以将fstream对象设置为在每次调用<<
- 如何从C#将对象设置为C++
- 哪个更好?如果子对象是类的成员,则为子对象设置父对象
- c++无法为包含静态变量的对象设置NULL指针
- 将数组中的对象设置为新对象
- 在OpenGL中为不同的对象设置单独的材质属性