如何在类中的其他方法中访问私有数据成员 2D 数组

How can I access a private data member 2D array in other methods within the class?

本文关键字:数据成员 数组 2D 访问 其他 方法      更新时间:2023-10-16

这段代码来自我的"魔方"生成器的头文件。 我试图通过构造函数设置私有成员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];