gpt4 book ai didi

c++ - 我可以在 C++ 中返回选定的引用吗?

转载 作者:太空宇宙 更新时间:2023-11-04 15:01:09 26 4
gpt4 key购买 nike

请看下面的 sudo 代码。

Object& getObjectDependingOnMonth(std::string& month, std::vector<Object>& vec) {

if (month == "January") {
auto& ref = vec.at(1);
} else {
auto& ref = vec.at(2);
}

ref.do_something(); // error because ref is local in block above.

return ref; // error because ref is local in block above.
}

上面的代码显示了我想要做什么。我想获得 vector 元素的引用。这取决于输入,月份。我想在函数 getObjectDependingOnMonth(...) 之外使用它的引用。但是我想不出如何在没有 block 中重复代码的情况下返回 vector 中选定元素的有效引用。 auto& ref = ... 在 if block 中定义。引用在其 block 之外无效。

我可以从函数返回选定的引用吗?非常感谢。

最佳答案

只需更改代码:

if (month == "January") {
auto& ref = vec.at(1);
} else {
auto& ref = vec.at(2);
}

引用以下内容,以便您引用

auto& ref = vec.at(month == "January" ? 1 : 2);

关于c++ - 我可以在 C++ 中返回选定的引用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42050856/

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