このコードは、「Magic Square」ジェネレータのヘッダーファイルにあります。プライベートメンバーをint ** squareのコンストラクタに設定しようとしましたが、配列を返すか、またはメソッドを使って出力しようとすると、コンストラクタで設定されていない異なるintの2次元配列が返されます。私の方法で配列を評価するにはどうすればいいですか?申し訳ありませんクラス内の他のメソッドでプライベートデータメンバー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;
}
}
コードの一部が不完全にフォーマットされている場合、私はStackOverflowのに新しいですし、どのようにすべての作品に慣れます。 コンストラクタ内の
参照:[MCVE](http://stackoverflow.com/help/mcve)。自分の問題をMCVEに絞って少し努力していたら、おそらく自分で解決するでしょう。 – cubuspl42