【问题标题】:loop through multiple classes循环多个类
【发布时间】:2017-01-15 17:55:43
【问题描述】:

在我的代码中有几个类

class samples{
some_public_variables
} a, b, c;

我想问有没有办法循环遍历所有这些类,像这样

for(i=0; i<number_of_classes; i++){
    class[i].variable.do_something   }

提前致谢!

【问题讨论】:

  • 不,没有。现在,这里真正的问题是什么。不,不是您要问的那个,而是您认为解决方案就是您要问的那个。
  • 好的!谢谢!我会尝试考虑不同的方法!
  • 你的代码中只有一个类,三个变量是类的实例。
  • 您的意思是像此类示例{} a[3]; 之类的东西吗?这似乎适用于 g++ 和 clang++,但我从未见过。

标签: c++ class loops iterator


【解决方案1】:

你可能想要这样的东西:

class samples{
    void foo() const;
};

samples a, b, c;

for (const auto& s : { std::ref(a), std::ref(b), std::ref(c) }) {
    s.foo();
}

【讨论】:

    【解决方案2】:

    ...或者同样可怕...

    int main()
    {
        class samples{
        public:
            samples(int x, int y, int z) : x(x), y(y), z(z) {}
            int x, y , z;
        }
        a { 1, 2, 3 },
        b { 4, 5, 6},
        c { 7, 8, 9 };
    
        for (auto& s : { &a, &b, &c })
        {
            std::cout << s->x << " " << s->y << " " << s->z << '\n';
        }
    }
    

    【讨论】:

      【解决方案3】:

      如果您想迭代执行相同操作的不同类,请使用多态性来完成。您可以创建一个抽象类来为您的其他类创建接口,如下所示:

      class MyInterface {
      
          public:
              /* Common method that must be implemented by all children classes */
              virtual void doSomething() = 0;
       };
      

      然后你为你的每个类实现特定的方法。

      class MyClassA : public MyInterface {
      
          public:
              void doSomething() { /* Implementation for class A */ }
      };
      
      class MyClassB : public MyInteface {
      
          public:
              void doSomething() { /* Implementation for class B */ }
      };
      

      之后,您可以使用通用接口和调用通用方法来迭代您的类。像这样:

      std::vector<MyInterface> classes;
      // Fill your vector with instances of your classes.
      for (int i = 0; i < classes.size(); ++i) {
          classes.doSomething();
      }
      

      希望对您的问题有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-11-06
        • 2015-03-10
        • 2014-05-22
        • 1970-01-01
        • 2011-08-09
        • 1970-01-01
        相关资源
        最近更新 更多