C++ 如何简化这段代码使得一个变量在用户输入之后才被声明
问题描述
我写了下面的代码:
#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;
在这个示例中,必须重复两次。(如果存在多个形状类,则需要重复更多次)
解决方案
解决方案通常是在知道要使用的类型之后动态地创建对象,并使用虚拟方法处理不同类型之间的共同交互,例如:
#include <iostream>
using namespace std;
class Shape {
public :
float lgth;
void getLgth() { cin >> lgth; }
virtual float calcArea() = 0;
};
class Square : public Shape {
public :
float calcArea() override { return lgth * lgth; }
};
class Circle : public Shape {
public :
float calcArea() override { return 3.14 * lgth * lgth; }
};
int main() {
char shape_type;
Shape* my_shape;
cout << "Shape Type (c/s) ? ";
cin >> shape_type;
if (shape_type == 'c') {
my_shape = new Circle;
}
else if (shape_type == 's') {
my_shape = new Square;
}
else {
cout << "Unknown type!" << endl;
return -1;
}
cout << "Shape Length ? ";
my_shape->getLgth();
cout << "Shape Area : " << my_shape->calcArea() << endl;
delete my_shape;
return 0;
}
注意,在现代C++中,你应该使用智能指针,比如 std::unique_ptr
,而不是直接使用 new
/ delete
,例如:
#include <iostream>
#include <memory>
using namespace std;
class Shape {
public :
float lgth;
void getLgth() { cin >> lgth; }
virtual float calcArea() = 0;
};
class Square : public Shape {
public :
float calcArea() override { return lgth * lgth; }
};
class Circle : public Shape {
public :
float calcArea() override { return 3.14 * lgth * lgth; }
};
int main() {
char shape_type;
unique_ptr<Shape> my_shape;
cout << "Shape Type (c/s) ? ";
cin >> shape_type;
if (shape_type == 'c') {
my_shape = make_unique<Circle>();
}
else if (shape_type == 's') {
my_shape = make_unique<Square>();
}
else {
cout << "Unknown type!" << endl;
return -1;
}
cout << "Shape Length ? ";
my_shape->getLgth();
cout << "Shape Area : " << my_shape->calcArea() << endl;
return 0;
}