简体   繁体   English

你可以在没有列表或向量的情况下迭代类对象吗?

[英]Can you iterate through class objects without a list or vector?

Suppose you have a class Class and you create 2 objects 假设您有一个类Class,并创建了2个对象

  Class *obj1 = new Class();
  Class *obj2 = new Class();

I know you can create a list and push_back the objects and then call 我知道你可以创建一个列表并推送对象,然后调用

  for (auto i : list_name) i->function();

but is there a way to iterate like this? 但有没有办法像这样迭代?

  for(auto i:Class) i->function();

Yes you can: 是的你可以:

for( auto i : { obj1, obj2 } ) i->function();

live example 实例

No you can not use a class name in place of a range_expression inside a range based loop as class does not represent a container nor a range of values. 不可以在基于范围的循环中使用类名来代替range_expression,因为类不表示容器,也不表示值范围。 You have freestanding instances of Class . 你有独立的Class实例。 You would need to store your instances in one of the following: 您需要将实例存储在以下某个中:

  • either an array or 无论是数组还是数组
  • an object for which begin and end member functions or free functions are defined or 定义了开始和结束成员函数或自由函数的对象
  • a braced-init-list 一个braced-init-list

and then use one of those inside a range based loop. 然后在基于范围的循环中使用其中一个。

Not exactly clear what you want, but you can also register all instances of your Class (if it's yours): 不完全清楚你想要什么,但你也可以注册你的Class所有实例(如果它是你的):

class Class {
  public:
    static std::set<Class*> instances;
    Class() { instances.insert(this); }
    ~Class() { instances.erase(instances.find(this)); }
    void function();
};
std::set<Class*> Class::instances;

and then iterate over all live Class instances as follows: 然后迭代所有实时Class实例,如下所示:

Class c;
auto upc = std::make_unique<Class>();
std::vector<Class> vc(4);

for (auto i : Class::instances)
  i->function();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM