0

我一直在尝试像在 C++ 中的 C# 中一样创建 Convert.To 命令,但我不想像“IntToString”那样做,而是像在 C# 中一样让它像“ToString”一样。我想知道如何知道函数内部给出的参数的格式?或者有没有其他方法可以做到这一点?

#include <iostream>
#include <sstream>

class converting {
public:
    std::string Int32ToString(int x) {
        std::stringstream asd;
        asd << x;
        std::string cnvrtd;
        asd >> cnvrtd;
        return cnvrtd;
    }
    int StringToInt32(std::string x) {
        std::stringstream asdf(x);
        int cnvrtd;
        asdf >> cnvrtd;
        return cnvrtd;
    }
};

int main() {
    converting Convert;
    std::cout << "This is for a test. Avaiable options are:" << std::endl << "StringToInt32" << std::endl << "Int32ToString" << std::endl;
    std::string firstinput;
    std::cin >> firstinput;
    if (firstinput == "StringToInt32") {
        std::string input;
        int result;
        std::cin >> input;
        result = Convert.StringToInt32(input);
        std::cout << result;
        return 0;
    }
    else if (firstinput == "Int32ToString") {
        int input;
        std::string result;
        std::cin >> input;
        result = Convert.Int32ToString(input);
        std::cout << result;
        return 0;
    }
    else {
        std::cout << "Please enter a valid input";
        return 0;
    }
}
4

1 回答 1

1

当您说-函数内部给定参数的格式时,您的意思是,您如何知道参数的数据类型。如果是这种情况,您将必须为要支持转换的所有数据类型编写函数,在具有相同函数名称的 Converting 类中,这在 C++ 中称为函数重载。例如

std::string convert (int n){}
std::string convert (float n){}
std::string convert (double n){}

当你调用这个转换函数时,编译器会根据数据类型选择合适的重载函数。

但是,通过编写模板函数来实现相同功能的更小方法

template<class Dt>
std::string Convert (Dt n){
    return std::to_string(n);
}

如果您提到了任何限制,希望我不会错过。

于 2021-01-10T19:32:03.403 回答