【问题标题】:how to know the size of the array while initializing an object using this array?使用此数组初始化对象时如何知道数组的大小?
【发布时间】:2015-05-02 10:33:07
【问题描述】:

问题是:定义动作对象的容器(可能是模板)(将被命名为 Runner)。动作对象 (AO) 是执行用户提供的功能的对象。这个想法是,一旦动作容器加载了 AO,就可以要求它运行或执行它们。执行结果在 Results 数组中返回。示例:

 AO a1(mul, x, x); //if run method is called it returns x*x
 AO a2(add, y, 1); //if run method is called it returns y+1
 AO a3(print, s); //if run method is called it prints s on cout

 Runner<AO> r = {a1,a2,a3};

所以现在在运行器类中我应该如何实现一个构造函数,它接受常量数组并知道它的大小

 template<typename a>
 class runner{
 a* m;
 int size;
public:
runner(const a x[]){
//how to know the size of x[] to initialize m=new a[size] and then fill it with a1,a2,a3 ??
}

【问题讨论】:

标签: c++ arrays class initialization


【解决方案1】:

数组无法知道它的大小,因此您应该将它作为参数传递给构造函数。
更简单:使用std::vector。使用方便的std::initializer_list,您可以使用大括号初始化器{} 继续初始化您的对象。举个例子:

#include <iostream>
#include <vector>
#include <initializer_list>

template<typename a>
class runner{
private:
    std::vector<a> objects;
public:
    runner(std::initializer_list<a> init) {
         objects.insert(objects.end(), init.begin(), init.end());
    }
    void iterate() {
        for(auto obj : objects)
            std::cout << obj << std::endl;
    }
};

int main() {
    //As template type I've chosen int, you can choose your own class AO aswell
    //This calls the constructor with the std::initializer_list
    runner<int> test = {1,2,3,4,7,0};
    test.iterate();
    return 0;
}

【讨论】:

    【解决方案2】:

    你可以做的是把所有的对象都推到一个向量中,然后把它传递给Ctor。

    按照以下步骤操作:

    包括:

    #include<vector>
    

    在 main() 中: 声明AO类的对象并推送到vector&lt;AO&gt; x

    AO a1(mul, x, x); //if run method is called it returns x*x
    AO a2(add, y, 1); //if run method is called it returns y+1
    AO a3(print, s);
    
    vector<AO> x;
    x.push_back(a1);
    x.push_back(a2);
    x.push_back(a3);
    
    Runner<AO> r(x);
    

    修改模板类

    class Runner{
        a* m;
        int size;
    public:
        Runner(vector<a> x)
        {
            m = new a[x.size()];
            for (int i = 0; i < x.size(); i++)
            {
                m[i] = x.at(i);
            }
        }
    };
    

    希望这真的是你想要的

    【讨论】:

      猜你喜欢
      • 2011-05-30
      • 2023-02-20
      • 2017-03-26
      • 1970-01-01
      • 2017-08-03
      • 1970-01-01
      • 2014-04-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多