gpt4 book ai didi

c++ - 如何转换 std::make_unique 以便我可以使用类中声明的函数?

转载 作者:行者123 更新时间:2023-11-28 00:00:35 25 4
gpt4 key购买 nike

或者我需要投 std::make_unique变成任何形式?

我有一个 FOO 类,其中包含一些我可以使用的函数:

 FOO::FOO(const yoo &yoo, float numbers) :
num_to_execute(numbers)
{
...
...
}

void FOO::execute()
{
execute(num_to_execute);
}

在另一个 .cpp 中,我给定的代码使用以下方法启动 foo:

 new_foo = std::make_unique<FOO>(yoo, number);

(到目前为止一切都是正确的)。我想要做的是在我的 new_foo 上调用 execute。我试过

 new_foo.execute();

但是它说:

  error: 'class std::unique_ptr<WORK::TOBEDONE::FOO>' has no member named 'EXECUTE'

execute应该可以拜访成员(member)<WORK::TOBEDONE::FOO>但是 std::unique_ptr 让我很难理解我应该做什么。

最佳答案

new_foo->execute();

unique_ptr 在这个意义上就像一个常规指针,并且有一个 operator->operator * 重载。

您在使用 时使用常规点 (.) 访问 unique_ptr 函数(如 std::unique_ptr::get) >->* 访问指针对象。

auto str = std::make_unique<std::string>("hello world");
auto i = std::make_unique<int>(5);

str->size();
*i = 4;
str.reset(); //deletes the pointee and make str point to null
i.reset(); //as above

关于c++ - 如何转换 std::make_unique 以便我可以使用类中声明的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39391599/

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