Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: sudoku (copy board)

Tags:

c++

sudoku

I'm new to c++ and got a problem when doing homework (sudoku).

Instruction said: "you have to create a new board being a copy of the current board (use the copy constructor and allocate the board from the heap with new)."

I've tried (it's wriiten in board.cc):

#include "board.h"

// Search for a solution, returns NULL if no solution found
Board* Board::search(void) {
  Board b = new Board(&this);
  ...
  return b;
}

Got error msg:

lvalue required as unary '&' operand.

I've also tried:

Board* Board::search(void) {
   Board b;
   Board *b3;
   b3 = &b;
...
   return b3;
}

This got no prob when comp. but it doesn't work either when running.

How to do it? Really need help here, thx!

Here is some code for board.h:

class Board {
private:
  Field fs[9][9]; // All fields on board

public:
  // Initialize board
  Board(void) {
    // Uses the default constructor of Field!
  }
  // Copy board
  Board(const Board& b) {
    for(int i = 0; i < 9; i++){
      for(int j = 0; j < 9; j++){
          fs[i][j] = b.fs[i][j];
      }
    }
  }

  // Assignment operator for board
  Board& operator=(const Board& b) {
    if(this != &b){
       for(int i = 0; i < 9; i++){
          for(int j = 0; j < 9; j++){
             fs[i][j] = b.fs[i][j];
          }
        }
     }
     return *this;
   }
   ....

Complete instruction can been found here: http://www.kth.se/polopoly_fs/1.136980!/Menu/general/column-content/attachment/2-2.pdf

Code: http://www.kth.se/polopoly_fs/1.136981!/Menu/general/column-content/attachment/2-2.zip

like image 211
Ferry Avatar asked Dec 16 '22 06:12

Ferry


2 Answers

Change:

Board b = new Board(&this);

to:

Board *b = new Board(*this);
like image 116
Paul R Avatar answered Dec 30 '22 18:12

Paul R


Board b = new Board(&this);

That line has two errors, the first one is that if you allocate with new, the type will be Board *, and not just Board. The second error is that if you want to use the copy constructor you should pass the element pointed by this, not the address of this:

Board * b = new Board( *this );
like image 33
David Rodríguez - dribeas Avatar answered Dec 30 '22 18:12

David Rodríguez - dribeas