C ++ - 自定义类型的交换功能不起作用

时间:2013-03-18 17:46:44

标签: c++ class function swap

我目前正在用C ++编写n-puzzle,虽然由于某种原因我无法交换电路板的元素。让我解释。我有一个“Piece”类(该类的一些方法):

Piece::Piece(int l, int c, int n):
line(l), 
column(c), 
number(n)
{

}

int Piece::getLine()
{
  return line;
}

int Piece::getColumn() const
{
  return column;
}

int Piece::getNumber() const
{
  return number;
}

void Piece::setLine(const int new_line)
{
  this -> line = new_line;
}

void Piece::setColumn(const int new_column)
{
  this -> column = new_column;
}

void Piece::setNumber(const int new_number)
{
  this -> number = new_number;
}

我还有一个执行游戏的Board类。该板是“片段”类型的向量的向量。正在使用以下代码创建该板:

for(size_t i = 0; i < this -> width; i++)
  {
    vector<Piece> row;

    for(size_t j = 0; j < this -> height; j++)
    {
      row.push_back(Piece(i, j, ((j == this -> width - 1) && (i == this -> height - 1) ? 0 : i * this -> width + j + 1)));
    }  
    board.push_back(row);
  }

直到这里没有错。问题是当我想交换董事会的两个要素时。想象一下,我们有一个3x3游戏。如果我运行以下代码,结果将是错误的

swapPieces(board[0][0], board[1][0]);
swapPieces(board[1][0], board[2][0]);
cout << board[0][0] << "\t" << board[0][0].getLine() << endl;

这个谜题是正确的:

4 2 3

7 5 6

1 8 0

但是通过执行board [0] [0] .getLine(),输出为1,这是Piece的初始位置!我真的不知道我做错了什么。如果有人能帮助我,我会很感激。)

编辑:swapPieces添加:

void Board::swapPieces(Piece &p1, Piece &p2)
{
  Piece p = p1;
  p1 = p2;
  p2 = p;
}

3 个答案:

答案 0 :(得分:3)

代码库确实有两种表示Piece位置的方法。一个是Piece对象中的“line”和“column”变量,另一个是Board和Vector行容器中Piece对象的排序。编程的基本原则是DRY(不要重复自己)。它会像你现在遇到的那样导致错误。 swapPieces可能正在交换容器中的对象,但不会更新对象变量。您可以通过使两个表示形式保持一致(设置行和列变量)来在swapPieces代码中对此进行修补,但从长远来看,确定两者中的哪一个是多余的将更加清晰。

答案 1 :(得分:0)

swapPieces似乎有效,但除非您同时致电setLinesetColumn,否则这些作品将不会知道它们已被移动。现在,这些片段将包含它们在构造函数中设置的原始位置。

答案 2 :(得分:0)

首先确保您的副本c'tor实际被调用(我还没有看到实现)。 第二,确保当您拍摄棋盘[0] [0]时,您将获取实际的对象而不是它的副本