C++ 如何将数组传递给构造函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9426932/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 12:48:26  来源:igfitidea点击:

How do I pass an array to a constructor?

c++arraysvisual-c++constructor

提问by Svad Histhana

I want to pass an array to a constructor, but only the first value is passed--the rest looks like garbage.

我想将数组传递给构造函数,但只传递第一个值——其余的看起来像垃圾。

Here's a simplified version of what I'm working on:

这是我正在处理的简化版本:

#include <iostream>

class board
{
    public:
        int state[64];
        board(int arr[])
        {
            *state = *arr;
        }
        void print();
};

void board::print()
{
    for (int y=0; y<8; y++)
    {
        for (int x=0; x<8; x++)
            std::cout << state[x + y*8] << " ";
        std::cout << "\n";
    }
}

int main()
{
    int test[64] = {
        0, 1, 2, 3, 4, 5, 6, 7,
        1, 2, 3, 4, 5, 6, 7, 8,
        2, 3, 4, 5, 6, 7, 8, 9,
        3, 4, 5, 6, 7, 8, 9,10,
        4, 5, 6, 7, 8, 9,10,11,
        5, 6, 7, 8, 9,10,11,12,
        6, 7, 8, 9,10,11,12,13,
        7, 8, 9,10,11,12,13,14 };

    board b(test);
    b.print();

    std::cin.get();
    return 0;
}

Can someone explain why this doesn't work and how to properly pass an array? Also, I don't want to copy the array. (And do I really have to indent every line by 4 spaces for code? That's pretty tedious.)

有人可以解释为什么这不起作用以及如何正确传递数组吗?另外,我不想复制数组。(我真的必须为代码将每一行缩进 4 个空格吗?这很乏味。)

回答by Michael Burr

In this case it might be best to use a reference to the array:

在这种情况下,最好使用对数组的引用:

class board
{
    int (&state)[64];

public:
    board(int (&arr)[64]) 
        : state(arr)
    {}

    // initialize use a pointer to an array
    board(int (*p)[64]) 
        : state(*p)
    {}


    void print();
};

A couple of advantages - no copying of the array, and the compiler will enforce that the correct size array is passed in.

几个优点 - 不复制数组,编译器将强制传入正确大小的数组。

The drawbacks are that the array you initialize the boardobject with needs to live at least as long as the object and any changes made to the array outside of the object are 'reflected' into the object's state. but those drawbacks occur if you use a pointer to the original array as well (basically, only copying the array will eliminate those drawbacks).

缺点是您初始化board对象的数组需要至少存在,只要对象和对对象外部的数组所做的任何更改都“反映”到对象的状态。但是如果您也使用指向原始数组的指针,则会出现这些缺点(基本上,只有复制数组才能消除这些缺点)。

One additional drawback is that you can'tcreate the object using a pointer to an array element (which is what array function parameters 'decay' to if the array size isn't provided in the parameter's declaration). For example, if the array is passed through a function parameter that's really a pointer, and you want that function to be able to create a boardobject referring to that array.

另一个缺点是您无法使用指向数组元素的指针创建对象(如果参数声明中未提供数组大小,则数组函数参数会“衰减”到什么程度)。例如,如果数组通过一个实际上是指针的函数参数传递,并且您希望该函数能够创建board引用该数组的对象。

回答by Seth Carnegie

Attempting to pass an array to a function results in passing a pointer to the first element of the array.

尝试将数组传递给函数会导致传递指向数组第一个元素的指针。

You can't assign arrays, and taking a parameter like T[]is the same as T*. So

您不能分配数组,并且采用类似参数T[]T*. 所以

*state = *arr;

Is dereferencing the pointers to stateand arrand assigning the first element of arrto the first element of state.

正在取消对state和的指针的引用arr,并将 的第一个元素分配给 的第arr一个元素state

If what you want to do is copy the values from one array to another, you can use std::copy:

如果您想要做的是将值从一个数组复制到另一个数组,您可以使用std::copy

std::copy(arr, arr + 64, state); // this assumes that the array size will
                                 // ALWAYS be 64

Alternatively, you should look at std::array<int>, which behaves exactly like you were assuming arrays behave:

或者,您应该查看std::array<int>,它的行为与您假设数组的行为完全一样:

#include <array>
#include <algorithm>
#include <iostream> 

class board
{
    public:
        std::array<int, 64> state;

        board(const std::array<int, 64> arr) // or initialiser list : state(arr)
        {
            state = arr; // we can assign std::arrays
        }
        void print();
};

void board::print()
{
    for (int y=0; y<8; y++)
    {
        for (int x=0; x<8; x++)
            std::cout << state[x + y*8] << " ";
        std::cout << "\n";
    }
}

int main()
{
    // using this array to initialise the std::array 'test' below
    int arr[] = {
        0, 1, 2, 3, 4, 5, 6, 7,
        1, 2, 3, 4, 5, 6, 7, 8,
        2, 3, 4, 5, 6, 7, 8, 9,
        3, 4, 5, 6, 7, 8, 9,10,
        4, 5, 6, 7, 8, 9,10,11,
        5, 6, 7, 8, 9,10,11,12,
        6, 7, 8, 9,10,11,12,13,
        7, 8, 9,10,11,12,13,14 };

    std::array<int, 64> test(std::begin(arr), std::end(arr));

    board b(test);
    b.print();

    std::cin.get();
    return 0;
}

回答by Rohit Vipin Mathews

#include <iostream>

class board
{
    public:
        int * state;    //changed here, you can also use **state
        board(int *arr)               //changed here
        {
          state = arr;
        }
        void print();
};

void board::print()
{
    for (int y=0; y<8; y++)
    {
        for (int x=0; x<8; x++)
            std::cout << *(state + x + y*8) << " ";   //changed here
        std::cout << "\n";
    }
}

int main()
{
    int test[64] = {
        0, 1, 2, 3, 4, 5, 6, 7,
        1, 2, 3, 4, 5, 6, 7, 8,
        2, 3, 4, 5, 6, 7, 8, 9,
        3, 4, 5, 6, 7, 8, 9,10,
        4, 5, 6, 7, 8, 9,10,11,
        5, 6, 7, 8, 9,10,11,12,
        6, 7, 8, 9,10,11,12,13,
        7, 8, 9,10,11,12,13,14 };

    board b(test);
    b.print();

    std::cin.get();
    return 0;
}

or you can use it as:

或者您可以将其用作:

class board
{
    public:
        int state[64];
        board(int arr[])
        {
            for(int i=0;i<64;++i)
               state[i] = arr[i];
        }
        void print();
};

EDIT 1: stable solution

编辑 1:稳定的解决方案

class board
    {
        public:
            int * state;    //changed here, you can also use **state
            board(int *arr)               //changed here
            {
              state = new int[64];
              for(int i=0;i<64;++i)
                   state[i] = arr[i];
            }
            void print();
    };

回答by vvnraman

The name of an array is the address of the first element in it.

数组的名称是其中第一个元素的地址。

Hence the line *state = *arrwill set state[0]to arr[0].

因此该行将*state = *arr设置state[0]arr[0]

Since right now you have defined stateas int state[64];, stateis const pointerof type intwhose address cannot be changed.

由于现在您已定义stateint state[64];,state是其地址无法更改const pointer的类型int

You can change it to int *state;and then state = arrwill work.

您可以将其更改为int *state;然后state = arr将工作。

回答by angryInsomniac

*arr gives the value that is stored at arr[0] . In c++ , the name of the array is a pointer to the first element in the array.

*arr 给出存储在 arr[0] 的值。在 c++ 中,数组的名称是指向数组中第一个元素的指针。

So when you do *state = *arr , you store the value at arr[0] in the variable state.

因此,当您执行 *state = *arr 时,您将 arr[0] 处的值存储在变量 state 中。

Now , if you want to pass the array without having to copy each element explicitly , I suggest that you make another array of the same size in the method which you are calling and then pass the name of the array from the caller , in essence :

现在,如果您想传递数组而不必显式复制每个元素,我建议您在调用的方法中创建另一个相同大小的数组,然后从调用者传递数组的名称,本质上:

methodWhereArrayisPassed(int *arrayName)
{
    int arrCopy[64];
    arrCopy = arrayName;

// Do more stuff here
}

methodWhichPassesArray()
{
    // do stuff here
    int arr[] = {
       0, 1, 2, 3, 4, 5, 6, 7,
       1, 2, 3, 4, 5, 6, 7, 8,
       2, 3, 4, 5, 6, 7, 8, 9,
       3, 4, 5, 6, 7, 8, 9,10,
       4, 5, 6, 7, 8, 9,10,11,
       5, 6, 7, 8, 9,10,11,12,
       6, 7, 8, 9,10,11,12,13,
       7, 8, 9,10,11,12,13,14 };

methodWhereArrayisPassed(arr);

// do stuff here
}

回答by Avi

*state = *arr;is using dereferencing, which returns the value at the address of the pointer.

*state = *arr;正在使用解引用,它返回指针地址处的值。

This is the same as state[0] = *arr;because *arris an int.

这与state[0] = *arr;因为*arr是一个int.

See this articlefor info on pointers. See the deference section.

有关指针的信息,请参阅此文章。请参阅尊重部分。

To solve this problem you want to do this:

要解决此问题,您需要执行以下操作:

for (int i = 0; i < 64; i++) state[i] = arr[i]