2

使用下面的代码时,它将 Tile 对象的 x 值设置为 i,将 y 值设置为 j。但如果我只打印 y 值正确的值,则 x 值始终为 4095。

代码:

主要代码:

Tile * tiles = new Tile[4096,4096];
    for(int i = 0; i< 4096;i++)
    {
        for(int j = 0;j< 4096;j++)
        {
            tiles[i,j].x = i;
            tiles[i,j].y = j;
        }
    }

    for(int i = 0; i< 4096;i++)
    {
        for(int j = 0;j< 4096;j++)
        {
                cout << "X (Should be " <<i<<"): "<< tiles[i,j].x << " " << "Y (Should be " <<j<<"): "<< tiles[i,j].y << "\n";
        }
    }

瓷砖.h:

#pragma once

class Tile
{
    public:
        int x, y;
};
4

1 回答 1

10

您没有正确使用数组:

i,j将始终返回j,因为这是逗号运算符的结果。

Tile** tiles = new Tile*[4096];
for(int i = 0; i < 4096; i++)
    tiles[i] = new Tile[4096];

    for(int i = 0; i< 4096;i++)
    {
        for(int j = 0;j< 4096;j++)
        {
            tiles[i][j].x = i;
            tiles[i][j].y = j;
        }
    }

    for(int i = 0; i< 4096;i++)
    {
        for(int j = 0;j< 4096;j++)
        {
                cout << "X (Should be " <<i<<"): "<< tiles[i][j].x << " " << "Y (Should be " <<j<<"): "<< tiles[i][j].y << "\n";
        }
    }


   // Destruction! DON'T FORGET!
   for(int i = 0; i < 4096; i++)
       delete[] tiles[i];
   delete[] tiles; 

如果您从逗号运算符计算值,您的原始代码将是:

Tile * tiles = new Tile[4096]; // returned last 4096
    for(int i = 0; i< 4096;i++)
    {
        for(int j = 0;j< 4096;j++)
        {
            tiles[i,j].x = i; // the same as tiles[j].x = i;
            tiles[i,j].y = j; // the same as tiles[j].y = j;
        }
    }

///...
于 2013-08-22T07:50:01.363 回答