-2

我需要将一个指针数组传递给一个函数,在下面的示例中,有一个名为 base 的类和一个名为 pool 的指针数组。如何将数组池传递给名为 function 的函数?1)如果我希望能够更改原始指针数组。2)如果我只想传递指针数组的副本。

谢谢,

class base
{

};

void function (base * pool)
{

}


int main
{
    base *pool[40];

    function (pool[0]);

    return 0;
}
4

2 回答 2

3
class base
{
    public:
    int a;
};

void function (base ** pool)
{
    for (int i = 0 ; i < 40; ++i)
        cout<<pool[i]->a<<' ';
}


int main()
{
    base *pool[40];

    // Allocate 40 base objects and the 40 base pointers 
    // point to them respectively    
    for(int i = 0; i < 40; ++i)
    {
        pool[i] = new base;
        pool[i]->a = i;
    }
    function (pool);


    // free the 40 objects
    for(int i = 0; i < 40; ++i)
        delete pool[i];

    return 0;
}

我添加a成员只是作为示例。

更好的是

void function (base ** pool, int n)
{
    for (int i = 0 ; i < n; ++i)
        cout<<pool[i]->a<<' ';
}

function (pool, n);

传递数组的副本并不容易——尤其是在对象本身是动态分配的情况下。

于 2013-06-24T17:05:15.377 回答
1

要将数组传递给函数,并维护有关数组的类型信息,您可以使用模板:

template <unsigned N>
void function (base *(&pool)[N]) {
}

没有办法传递数组的副本,除非它在 ​​a structorclass中。在 C++11 中,您在 STL 中有这样一个类,称为array

#include <array>
template <unsigned N>
void function (std::array<base *, N> pool) {
    pool[0] = 0;
}

base b;
std::array<base *, 40> p;
p[0] = &b;
function(p);
assert(p[0] == &b);
于 2013-06-24T17:13:48.220 回答