当您声明数组时,test arr[9][9];
分配内存并为每个成员调用默认构造函数。所以你不需要调用new
来分配新的内存。我假设您的目标是test
使用从std::cin
.
然后你有几个选择:
它看起来像:
test* arr[9][9];
for(unsigned int i = 0; i < 9; i++)
{
for(unsigned int j = 0; j < 9; j++)
{
cin >> s[i][j];
arr[i][j] = new test(s[i][j]);
}
}
- 如果要保留普通
test
对象数组(没有指针),则可以使用:
提供一种test::set(int)
方法来设置构造后的值。
test arr[9][9];
for(unsigned int i = 0; i < 9; i++)
{
for(unsigned int j = 0; j < 9; j++)
{
cin >> s[i][j];
arr[i][j].set(s[i][j]);
}
}
operator=(const test&)
临时构造对象,然后使用(或operator=(test &&)
在 c++11 中)将其分配给数组中已分配的对象。请注意,这里没有new
:
test arr[9][9];
for(unsigned int i = 0; i < 9; i++)
{
for(unsigned int j = 0; j < 9; j++)
{
cin >> s[i][j];
arr[i][j] = test(s[i][j]);
}
}
或者使用placement new(这会在预分配的内存块中构造新对象):
test arr[9][9];
for(unsigned int i = 0; i < 9; i++)
{
for(unsigned int j = 0; j < 9; j++)
{
cin >> s[i][j];
new(&arr[i][j]) test(s[i][j]);
}
}
- 最后一个:如果您没有特定的理由使用静态二维数组,请使用一些 STL 容器。