在构造函数中传递指向数组的指针

Passing a pointer to an array in a constructor

我需要在构造函数中传递一个指向数组的指针(我知道许多人认为在 C++ 中使用普通数组是不好的做法,但现在我只想继续这样做)。

请考虑以下代码:

// let's omit includes

class A {
   // irrelevant
}

class B {
    public:
    //irrelevant
    void someMethod() {
        _c = new C(array_id);
    }

    private:
    C* _c;
    A* array_id[SOME_CONST];
}

class C {
    public:
    C(A* a_array) : _array(a_array) {}
    private:
    A* _array;
}

尝试编译将导致:

error: no matching function for call to C::C(A* [SOME_CONST])'

据我所知,数组的标识符衰减为指向数组首元素的指针,但似乎不能直接使用。如何在 C 的构造函数中有效地传递指向 A* 数组的指针?

您有两个问题:第一个是您使用 个指针数组 调用 C 构造函数,而不是数组。第二个问题是您试图将该分配分配给不兼容的类型。

解决方案可能类似于

class B
{
public:
    void someMethod()
    {
        my_c = new C(my_a_array);
    }

private:
    A my_a_array[SOME_CONST];
    C* my_c;
};

这将分配 C 类型的 单个 对象,将 A 对象的 数组 传递给它。

How can I effectively pass a pointer to an array of A* in the constructor of C?

C(array_id);

问题是 C 构造函数不接受 A* 的数组,它接受 A*.

如果要将 A* 的数组传递给 C 构造函数,则需要将其声明为采用 A**:

C(A** a_array)

或者,等价地:

C(A* a_array[])

根据 C++ 标准

4.2 Array-to-pointer conversion [conv.array]
An lvalue or rvalue of type “array of N T” or “array of unknown bound of T” can be converted to a prvalue of type “pointer to T”. The result is a pointer to the first element of the array.

像这样修改您的代码:

   class C {

        public:
        typedef A* PTA[SOME_CONST];
        C(PTA a_array) : _array(a_array) {}
        private:
        A** _array;//Note this line,type decays.
    };