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

如何用C++类模板实现自动适配用户输入类型的计算器

解决方案:基于类模板的动态类型匹配计算器

问题说明

需要实现一个支持加减乘除的C++类模板计算器,要求:

  • 支持int、float、double、char四种类型
  • 根据用户输入的数据类型,自动实例化对应类型的模板对象
  • 原代码固定实例化float类型,需修改以实现动态匹配

修改后的完整代码

#include <iostream>
#include <string>
#include <cctype>

using namespace std;

template <typename T>
class Calculator
{
public:
    T number1;
    T number2;

    // 统一接收输入的方法
    void accept()
    {
        cout << "Number 1: ";
        cin >> number1;
        cout << "\nNumber 2: ";
        cin >> number2;
    }

    void addition()
    {
        T sum = number1 + number2;
        cout << "Sum of the two numbers= " << sum << "\n";
    }

    void subtraction()
    {
        T diff = number1 - number2;
        cout << "Difference of the two numbers= " << diff << "\n";
    }

    void multiplication()
    {
        T prod = number1 * number2;
        cout << "Product of the two numbers= " << prod << "\n";
    }

    void division()
    {
        try
        {
            if (number2 == static_cast<T>(0))
            {
                throw number2;
            }
            T divi = number1 / number2;
            cout << "Division of the two numbers= " << divi << "\n";
        }
        catch (const T&)
        {
            cout << "Division by zero exception\n";
        }
    }
};

// 通用处理函数,复用不同类型的计算器逻辑
template <typename T>
void process_calculator(int choice)
{
    Calculator<T> calc;
    calc.accept();
    
    switch (choice)
    {
    case 1: calc.addition(); break;
    case 2: calc.subtraction(); break;
    case 3: calc.multiplication(); break;
    case 4: calc.division(); break;
    default: cout << "Invalid choice\n"; break;
    }
}

int main()
{
    cout << "*******************************************************************************************\n";
    cout << "Enter two variables to perform mathematical operations: \n";
    cout << "*******************************************************************************************\n";
    
    // 读取第一个输入的字符串,用于判断类型
    string input1;
    cout << "Number 1: ";
    cin >> input1;
    
    // 将读取的字符放回输入流,保证后续accept方法能正确读取原始输入
    cin.putback(' ');
    for (auto it = input1.rbegin(); it != input1.rend(); ++it)
    {
        cin.putback(*it);
    }

    int choice;
    cout << "\n*******************************************************************************************\n";
    cout << "Choose an operation to perform with the numbers: \n";
    cout << "1. Addition\n2. Subtraction\n3. Multiplication\n4. Division\n";
    cout << "*******************************************************************************************\n";
    cout << "Choice: ";
    cin >> choice;
    cout << "\n*******************************************************************************************\n\n";

    // 判断输入类型并调用对应处理逻辑
    bool is_char = (input1.size() == 1 && isalpha(input1[0]));
    bool is_int = true;
    bool is_float = false;
    bool is_double = false;

    if (!is_char)
    {
        for (char c : input1)
        {
            if (c == '.')
            {
                is_int = false;
                is_float = true;
            }
            else if (!isdigit(c) && c != '-' && c != '+')
            {
                is_int = false;
                is_float = false;
                break;
            }
        }
        // 区分float和double:带科学计数法或长度较长的浮点数视为double
        if (is_float && (input1.size() > 6 || input1.find('e') != string::npos || input1.find('E') != string::npos))
        {
            is_double = true;
            is_float = false;
        }
    }

    if (is_char)
    {
        process_calculator<char>(choice);
    }
    else if (is_int)
    {
        process_calculator<int>(choice);
    }
    else if (is_float)
    {
        process_calculator<float>(choice);
    }
    else if (is_double)
    {
        process_calculator<double>(choice);
    }
    else
    {
        cout << "Unsupported input type\n";
    }

    return 0;
}

关键修改说明

  • 模板类优化:
    • 完善accept()方法,统一处理不同类型的输入
    • 修改异常捕获逻辑,改为捕获模板类型const T&,适配所有支持的类型,避免原代码仅支持float捕获的局限
  • 动态类型匹配:
    • 通过读取输入字符串判断类型:单字母视为char,纯数字视为int,含小数点的短数字视为float,长浮点数或带科学计数法的视为double
    • 编写通用模板函数process_calculator<T>,复用不同类型计算器的业务逻辑,避免重复代码
  • 输入流处理:读取第一个输入字符串后,将字符放回输入流,确保后续accept()方法能正确读取原始输入值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 18:45:38