我如何通过一个数组来构造? [英] How do I pass an array to a constructor?

查看:164
本文介绍了我如何通过一个数组来构造?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想传递一个数组构造器,但只有前值传递 - 其余的看起来像垃圾

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;
}

有人可以解释为什么这不工作以及如何正确地传递数组?另外,我不想阵列复制。 (和我真的有4位为code缩进每行吗?这是pretty乏味。)

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.)

推荐答案

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

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 board object 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).

一个额外的缺点是你的不能的创建使用指针数组元素(这是什么样的对象数组函数参数衰变到如果不提供数组的大小参数的声明)。例如,如果数组是通过一个函数参数,它确实是一个指针过去了,你想要的功能,能够创建一个指的是阵列板对象。

One additional drawback is that you can't create 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 board object referring to that array.

这篇关于我如何通过一个数组来构造?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆