Sva*_*ana 15 c++ arrays constructor visual-c++
我想将一个数组传递给构造函数,但只传递第一个值 - 其余的看起来像垃圾.
这是我正在研究的简化版本:
#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;
}
Run Code Online (Sandbox Code Playgroud)
有人可以解释为什么这不起作用以及如何正确传递数组?另外,我不想复制数组.(我是否真的必须将每行代码缩进4个代码?这非常繁琐.)
在这种情况下,最好使用对数组的引用:
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();
};
Run Code Online (Sandbox Code Playgroud)
一些优点 - 不复制数组,编译器将强制传入正确的大小数组.
缺点是初始化board对象的数组需要至少与对象一样长,并且对象外部的数组所做的任何更改都会"反映"到对象的状态.但是如果你使用指向原始数组的指针也会出现这些缺点(基本上,只复制数组会消除这些缺点).
另一个缺点是你不能使用指向数组元素的指针来创建对象(如果参数声明中没有提供数组大小,则数组函数参数'衰减').例如,如果数组通过一个实际上是指针的函数参数传递,并且您希望该函数能够创建board引用该数组的对象.
尝试将数组传递给函数会导致将指针传递给数组的第一个元素.
您不能分配数组,并采取了类似的参数T[]是一样的T*.所以
*state = *arr;
Run Code Online (Sandbox Code Playgroud)
被取消引用指针state和arr和分配的第一要素arr来的第一个元素state.
如果您要做的是将值从一个数组复制到另一个数组,您可以使用std::copy:
std::copy(arr, arr + 64, state); // this assumes that the array size will
// ALWAYS be 64
Run Code Online (Sandbox Code Playgroud)
或者,您应该看一下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;
}
Run Code Online (Sandbox Code Playgroud)
*state = *arr;使用解引用,它返回指针地址处的值。
state[0] = *arr;这与because *arris an相同int。
有关指针的信息,请参阅这篇文章。请参阅参考部分。
为了解决这个问题,你需要这样做:
for (int i = 0; i < 64; i++) state[i] = arr[i]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
37217 次 |
| 最近记录: |