本文介绍了C ++:如何传递对象数组到函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个指向数组对象的指针。它看起来像:
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";
如何通过引用将myClass传递给函数?
How can I pass "myClass" to a function by reference? 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);
否则,使用 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);
我不会调用数组myClass。
I would not call an array "myClass" though.
这篇关于C ++:如何传递对象数组到函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!