[英]C++: How to pass array of objects into function?
I have a pointer to array of objects. 我有一个指向对象数组的指针。 It looks like:
看起来像:
MyClass *myClass[ 10 ];
myClass[ 0 ] = new MyClass(); // init for each of myClass[0..9]
myClass[ 0 ]->field1 = "hello";
How can I pass "myClass" to a function by reference? 如何通过引用将“ myClass”传递给函数? I tried a few cases but it didn't work.
我尝试了一些案例,但没有成功。
If you really must use an array, then 如果您确实必须使用数组,那么
template<size_t N >
void foo(MyClass (&arr)[N] )
{
// Access arr[i], size is N
}
...
foo(myClass);
Otherwise, use an std::array
否则,使用
std::array
template<size_t N >
void foo(std::array<MyClass,N>& arr )
{
// Access arr[i], size is N or arr.size()
}
...
std::array<MyClass, 10> myClass = ....;
foo(myClass);
I would not call an array "myClass" though. 我不会将数组称为“ myClass”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.