如何在使用此数组初始化对象时知道数组的大小
how to know the size of the array while initializing an object using this array?
问题说:定义一个动作对象的容器(可能是模板)(将被命名为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};
所以现在在 runner 类中,我应该如何实现一个接受常量数组并知道它大小的构造函数
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 ??
}
数组
无法知道它的大小,因此您应该将其作为参数传递给构造函数。
更简单:使用 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;
}
您可以做的是推送向量中的所有对象,然后将其传递给 Ctor。
请按照以下步骤操作:
包括:
#include<vector>
在主():声明类 AO
的对象并将它们推送到vector<AO> 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);
}
}
};
希望这真的是你想要的
相关文章:
- 销毁C++中动态分配的内存(数组对象)
- 数组对象的生存期是否在重用其元素存储时结束?
- 为什么顶点数组对象会导致错误?
- 具有纯虚函数和指针数组对象类型的父类的指针数组
- 这是使用构造函数初始化数组对象的最佳方法吗?
- OpenGL 顶点数组对象与 tinyobjloader
- 将数组/对象/结构列表从C#库中传递给C MFC应用程序
- C++ RapidJson 帮助反序列化数组对象
- ptrdiff_t可以表示指向同一数组对象元素的指针的所有减法吗?
- 检查成员函数是否返回临时对象或数组对象
- 为什么 std::variant 不能容纳数组对象类型,而联合可以?
- 当数组对象以函数参数传递时,为什么复制构造函数会自称
- 如何使用箭头指针打印出一类数组对象,这些对象中有多个分数
- C++17 std::shared_ptr<> 类数组对象的重载运算符 []
- 添加两个具有运算符重载的数组对象,从而导致分段错误
- opengl:两个不同的矢量可以绑定到同一个顶点数组对象吗
- 使用相同的数据填充数组对象或使用指针
- 方法用于最快的分配,并且不需要将动态大小的数组对象作为局部变量
- 如何将2d数组对象传递给c++中的函数
- ReferenceTable溢出(jni-android),数组对象释放