[英]How do I instantiate objects and have them still be available outside of their scope? (e.g. instantiated an object in a loop)
I'm trying to write a program that takes in user input and uses it to create objects that are then pushed to a list.我正在尝试编写一个程序,该程序接受用户输入并使用它来创建对象,然后将其推送到列表中。 Here is a simplified version of what I wrote:
这是我写的简化版本:
int main(){
cout << "How many lists? \n";
int numLists;
cin >> numLists;
list<MyObject> objectList;
for(int i = 0; i < numLists; i++){
cout << "Enter some input for list #" << i << "! \n";
int n = 3;
while(n-- != 0){
int input;
cin >> input;
MyObject object(input);
objectList.push_back(object);
}
//Save the newly created list somewhere
}
//Do something with all the created lists
}
Once the loop finishes, the objects created inside of the loop end up out of scope and the list has size zero.循环完成后,在循环内创建的对象最终会超出 scope 并且列表的大小为零。
I started using我开始使用
list<MyObject> *list = new list<MyObject>
...
MyObject *object = new MyObject(input);
...
(*list).push_back(*object);
and it seems to be working fine, but I was wondering if there was a better way to achieve this.它似乎工作正常,但我想知道是否有更好的方法来实现这一点。 Furthermore, since I am using multiple instances of list and MyObject outside of the loops from which they were created, how do I clear the memory?
此外,由于我在创建它们的循环之外使用 list 和 MyObject 的多个实例,我如何清除 memory?
Thank you谢谢
Read up on scope for C++ here: https://en.cppreference.com/w/cpp/language/scope在此处阅读 scope 的 C++: https://en.cppreference.com/w/cpp/language/scope
Why do you want to reference objects made in the for loop?为什么要引用在 for 循环中创建的对象? They have already been copied into the list<> object, so you can read/modify them there.
它们已经被复制到列表<> object,所以你可以在那里阅读/修改它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.