TwoDimensionalShape Class 应该包含什么?
What should the TwoDimensionalShape Class contain?
我正在尝试使用 C++ 中的多态性进行练习,以计算以下层次结构中图形的面积和体积
Shape
TwoDimensionalShape ThreeDimensional
Circle Square Triangle Sphere Cube
我在 Shape class 中声明了一个虚函数 getArea 和 getVolume,例如在 Circle class 中函数是:
double Circle::getArea() const
{
return 3.14*radius*radius;
}
其中半径在圆 class 中是私有的。
但我对我应该在 TwoDimensionalShape 中包含什么 class 以及是否应该在其中声明一个变量区域有些困惑。
您不需要中间级别内的数据成员类。它们只是为了层次抽象,为了说 Circle 是一个 TwoDimensionalShape。您稍后可能会有一些函数引用 TwoDimensionalShape
并且您可以在其中传递 Circle
或 Triangle
,但不能传递任何其他非 TwoDimensionalShape。
作为数据成员,您可以在 Shape
中设置一些标志。数据成员将指定当前对象的类型。你可以有相同的 enum
。这将用于静态断言和运行时检查。这在某些方面也可能有帮助,而不需要虚拟功能。
我正在尝试使用 C++ 中的多态性进行练习,以计算以下层次结构中图形的面积和体积
Shape
TwoDimensionalShape ThreeDimensional
Circle Square Triangle Sphere Cube
我在 Shape class 中声明了一个虚函数 getArea 和 getVolume,例如在 Circle class 中函数是:
double Circle::getArea() const
{
return 3.14*radius*radius;
}
其中半径在圆 class 中是私有的。
但我对我应该在 TwoDimensionalShape 中包含什么 class 以及是否应该在其中声明一个变量区域有些困惑。
您不需要中间级别内的数据成员类。它们只是为了层次抽象,为了说 Circle 是一个 TwoDimensionalShape。您稍后可能会有一些函数引用 TwoDimensionalShape
并且您可以在其中传递 Circle
或 Triangle
,但不能传递任何其他非 TwoDimensionalShape。
作为数据成员,您可以在 Shape
中设置一些标志。数据成员将指定当前对象的类型。你可以有相同的 enum
。这将用于静态断言和运行时检查。这在某些方面也可能有帮助,而不需要虚拟功能。