You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何简化C++中用户输入后声明变量导致的重复代码?

优化建议:利用C++多态消除重复代码

你代码里的重复交互逻辑,核心问题是没用到C++的多态特性来统一处理不同形状对象。下面是具体的优化方案:

步骤1:将Shape改为抽象基类

给父类Shape添加纯虚函数calcArea,把它变成抽象类——这样所有子类必须实现这个方法,同时我们可以通过基类的指针/引用调用子类的具体实现:

#include <iostream>
using namespace std;

class Shape {
public:
    float lgth;
    void getLgth() { cin >> lgth; }
    // 纯虚函数,定义形状的统一计算接口
    virtual float calcArea() const = 0;
};

class Square : public Shape {
public:
    // override关键字明确表示重写父类虚函数,避免写错
    float calcArea() const override { return lgth * lgth; }
};

class Circle : public Shape {
public:
    float calcArea() const override { return 3.14f * lgth * lgth; }
};

步骤2:抽离重复的交互逻辑

把重复的输入、计算、输出代码做成一个通用函数,接收Shape的引用,不管是Square还是Circle,都能复用这段逻辑:

void processShape(Shape& shape) {
    cout << "Shape Length ? ";
    shape.getLgth();
    cout << "Shape Area : " << shape.calcArea() << endl;
}

步骤3:重构main函数

在main里根据用户输入创建对应子类对象,然后调用通用函数处理,彻底消除重复代码:

int main() {
    char shape_type;
    cout << "Shape Type (c/s) ? ";
    cin >> shape_type;

    if (shape_type == 'c') {
        Circle my_shape;
        processShape(my_shape);
    } else if (shape_type == 's') {
        Square my_shape;
        processShape(my_shape);
    } else {
        cout << "Invalid shape type!" << endl;
    }

    return 0;
}

进阶优化:用智能指针管理对象(可选)

如果后续需要在更大作用域管理对象,建议用std::unique_ptr这类智能指针避免手动内存管理:

#include <memory> // 引入智能指针头文件

int main() {
    char shape_type;
    cout << "Shape Type (c/s) ? ";
    cin >> shape_type;

    unique_ptr<Shape> my_shape;
    if (shape_type == 'c') {
        my_shape = make_unique<Circle>();
    } else if (shape_type == 's') {
        my_shape = make_unique<Square>();
    } else {
        cout << "Invalid shape type!" << endl;
        return 1;
    }

    processShape(*my_shape);
    return 0;
}

优化的核心优势

  • 消除重复代码:新增其他形状(比如Triangle)时,只需要继承Shape并实现calcArea,原有逻辑完全不用改
  • 代码易维护:所有交互逻辑集中在processShape里,修改时只改一处
  • 符合开闭原则:对扩展开放(新增形状),对修改关闭(不动原有代码)

内容的提问来源于stack exchange,提问作者Stef1611

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 05:42:47