fun(int a) {
if (a) return a; return "empty";
}
我需要一个函数来获取一个数字,并根据它是哪个数字返回一个 int 变量或一个字符串。 请告诉我如何实现这样的功能。
最佳答案
使用 C++ 17,您可以使用 variant :
std::variant<int, std::string> fun(int a) {
if (a) return a; return "empty";
}
或者使用 optional 的结构:
struct r {
std::optional<int> i;
std::optional<std::string> s;
};
r fun(int a) {
r out;
if (a) out.i = a; else out.s = "empty";
return out;
}
或者对于先前的标准,使用带有指示有效性的字段的结构。
struct r {
enum class type {i, s};
int i;
std::string s;
type t;
};
r fun(int a) {
r out;
if (a) {
out.i = a;
out.t = r::type::i;
else {
out.s = "empty";
out.t = r::type::s;
}
return out;
}
关于C++ 可以根据接受的值返回两种类型之一的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59547137/