gpt4 book ai didi

c++ - 关于我的变量范围需要一些解释

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

/* simple class that has a vector of ints within it */
class A
{
public:
vector<int> int_list;
};

/* some function that just returns an int, defined elsewhere */
int foo();

/* I want to fill the object's int_list up */
A a_obj;

int main() {
for (int i = 0; i < 10; i++) {
int num = foo();
a_obj.int_list.push_back( num );
}
}

num 的范围是否仅限于 for 循环?退出for循环后会被销毁吗?如果我尝试访问 a_objint_list 中的数字,我将无法访问,因为其中的数字将被破坏吗?

最佳答案

Is the scope of num limited to the for loop?

Will it be destroyed once the for loop is exited?

它会在每次迭代后销毁,然后为下一次重新创建!

If I try to access the numbers in a_obj's int_list will I not be able to as the numbers inside will have been destroyed?

容器存储拷贝,因此您不必担心这一点。

你只会遇到引用和指针的这类问题。

关于c++ - 关于我的变量范围需要一些解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8063384/

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