我写了以下代码:
#include <iostream>
using namespace std;
class Shape {
public : float lgth;
public : void getLgth() { cin >> lgth;}
};
class Square : public Shape {
public : float calcArea() { return lgth * lgth; }
};
class Circle : public Shape {
public : float calcArea() { return 3.14 * lgth * lgth; }
};
int main() {
char shape_type;
cout <<"Shape Type (c/s) ? ";
cin >> shape_type;
if (shape_type == 'c') {
Circle my_shape;
cout << "Shape Length ? ";
my_shape.getLgth();
cout << "Shape Area : " << my_shape.calcArea() << endl;
}
else if (shape_type == 's') {
Square my_shape;
cout << "Shape Length ? ";
my_shape.getLgth();
cout << "Shape Area : " << my_shape.calcArea() << endl;
}
return 0;
}
由于形状的类型在执行开始时未知(询问用户),因此变量
my_shape
在if then else
语句中声明。之后这个变量只有在这个范围内才知道(我明白这一点)。所以,这部分代码:
cout << "Shape Length ? ";
my_shape.getLgth();
cout << "Shape Area : " << my_shape.calcArea() << endl;
在此示例中必须重复两次。(但如果存在许多形状类,则需要重复两次)。
我是 C++ 的初学者,但我认为这不是最好的方法。欢迎大家提出意见。谢谢
使用模板,您可以分解代码:
template <typename TShape>
void do_job()
{
TShape my_shape;
std::cout << "Shape Length ?";
my_shape.getLgth();
std::cout << "Shape Area : " << my_shape.calcArea() << std::endl;
}
在你的
main
中:
if (shape_type == 'c') {
do_job<Circle>();
} else if (shape_type == 's') {
do_job<Square>();
}
或更多类型
switch (shape_type) {
case 'c': do_job<Circle>(); break;
case 's': do_job<Square>(); break;
// ...
}