如何在类中的其他方法中访问私有数据成员 2D 数组
How can I access a private data member 2D array in other methods within the class?
这段代码来自我的"魔方"生成器的头文件。 我试图通过构造函数设置私有成员int**square,但是当我尝试返回数组或通过方法打印它时,它会返回一个不同整数的2D数组,而不是通过构造函数设置的。 我该怎么做才能通过我的方法访问数组。
class MagicSquare{
public:
MagicSquare(int sideLenght);
void printAllForms();
void setsideLenght(int num);
int**getMagicSquare();
void printSquare(int** square);
~MagicSquare();
private:
int sideLenght;
int**square;
};
//constructor
MagicSquare :: MagicSquare(int sideLenght)
{
this-> sideLenght = sideLenght;
//initialization of square and setting values to 0
int**square = new int*[sideLenght];
for(int i = 0; i !=sideLenght; i++)
square[i] = new int[sideLenght];
for(int i = 0; i<sideLenght; i++)
{
for(int j = 0; j<sideLenght; j++)
{
square[i][j] = 0;
}
}
//making the square magic
int row = sideLenght/2;
int col = sideLenght-1;
for(int i = 1; i<sideLenght*sideLenght+1;)
{
if(row == -1 && col == sideLenght)
{
row++;
col -= 2;
}else{
if(col == sideLenght)
col = 0;
if(row == -1)
row = sideLenght-1;
}
if(square[row][col] != 0)
{
col -= 2;
row++;
continue;
}else{
square[row][col] = i;
i++;
}
row--;
col++;
}
}
MagicSquare :: ~MagicSquare(){
if(square != NULL){
for(int i = 0; i < sideLenght; ++i){
delete[] square[i];
}
delete[] square;
}
}
//print original and rotated 2D array
void MagicSquare :: printAllForms(){
for(int i = 0; i<sideLenght; i++){
for(int j = 0; j<sideLenght; j++){
std::cout<<square[i][j]<<"t";
}
std::cout<<std::endl;
}
int**rotatedSquare = new int*[sideLenght];
for(int x=0; x<4; x++){
for(int i = 0; i<sideLenght; i++)
square[i] = new int[sideLenght];
for(int i=0; i<sideLenght; i++)
for(int j=0; j<sideLenght; j++)
rotatedSquare[i][j] = square[sideLenght-1-j][i];
for(int i = 0; i<sideLenght; i++){
for(int j = 0; j<sideLenght; j++){
std::cout<<rotatedSquare[i][j]<<"t";
}
std::cout<<std::endl;
}
}
}
void MagicSquare :: setsideLenght(int sideLenght){
this-> sideLenght = sideLenght;
}
int** MagicSquare :: getMagicSquare(){
return square;
}
//prints inputed 2D array
void MagicSquare :: printSquare(int**matrix){
for(int i = 0; i<sideLenght; i++){
for(int j = 0; j<sideLenght; j++){
std::cout<<matrix[i][j]<<"t";
}
std::cout<<std::endl;
}
}
抱歉,如果某些代码格式不正确,我是堆栈溢出的新手,并且习惯了它的工作原理。感谢您的帮助
构造
函数中的int**square = new int*[sideLenght];
正在创建一个隐藏成员的局部变量square
(因此永远不会设置成员(。请尝试square = new int*[sideLenght];
。
相关文章:
- 是否可以将结构数组别名为结构成员数组?
- C++:初始化 constexpr 构造函数中的成员数组
- 使用带有参数包的数组的成员数组初始化类
- C++ 在析构函数调用之前删除的动态成员数组
- 错误的值是使用c++从CSV文件数据写入数组
- c++用输入数据创建数组
- 初始化在类类型 #define 中定义的非静态成员数组,不带默认 ctor
- 指向具有不同大小的成员数组的指针
- 用另一个 constexpr 数组对成员数组进行大括号初始化
- 对象成员数组C++默认初始化
- 如何将数据从数组复制到C++特征矩阵或向量
- 如何在构造函数中的类成员数组中分配数组值,而无需使用STD库
- 将类成员数组组合到单个数组时性能下降
- 如何将数据从公共方法添加到同一类中的私有成员数组中?
- 如何在C 中的派生类中分配数据成员数组
- C 集合构建器中类成员数组的2D数组大小
- 如何在 c++ 中从对象数组中获取数据成员数组
- 在VS2012上将数据成员数组元素初始化为零
- 如何在所示代码中对类的两个数据成员数组进行排序
- 非静态数据成员(数组)的使用无效