gpt4 book ai didi

c++ - Java 在 C++ 中返回 null 的等价物是什么?

转载 作者:搜寻专家 更新时间:2023-10-30 23:51:03 25 4
gpt4 key购买 nike

我已经了解 Java,并且由于其他一些原因正在尝试学习 C++。在 Java 中的方法中,如果您没有任何返回值或根据您的逻辑有一个无法到达的返回行,但您只想让编译器满意,您只需返回 null。例如:

public static int[] /* This can be any Object, and returning null would work */ 5() {
for(int i = 0; i < 100; i++) {
if(i == 5) {
return new int[]{5}; // I don't know why you would want to do this, but I
// can't think of a better example.
}
}

// The compiler will give an error because there is
// no return statement, even though it is guaranteed
// to return {5}. So, for convenience, do this:

return null;
}

但是,如果我在 C++ 中执行 return NULL 或什至 return nullptr,它只会给出错误。有什么办法可以解决这个问题吗?

最佳答案

就像其他人指出的那样,有 nullptr .但是返回 nullptr意味着你的返回值是一个指针,这意味着你很可能在你的函数中有一个你可能不需要的堆分配。

从 C++ 17 开始,我们有 std::optional 您可以将其用作函数的返回类型。

给定任何非引用返回类型 T您可以将该返回类型更改为 std::optional<T>而不是 nullptr你返回 std::nullopt{} .

例子:

std::optional<std::string> foo(int x)
{
if (x > 10)
return "greater 10";

return std::nullopt; // or return {}
}

int main()
{
auto str = foo(12);

if (str) // check if str actually has a value or if it's null
std::cout << *str; // dereference to get the actual string
else
std::cout << "no string returned";

return 0;
}

关于c++ - Java 在 C++ 中返回 null 的等价物是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58366234/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com