如何将子类分配给函数中的抽象类指针?

时间:2012-03-07 23:11:43

标签: c++ pointers reference abstract-class object-slicing

void Player::move(Board &board, Solver &solver){
   Position* best = solver.find_best_move(&board);
   cout<<"Score: "<<best->get_score()<<endl;
   cout<<"Board: ";
   best->get_board()->print_board();
   board = *(best->get_board());
   Board * b(best->get_board());
   cout<<"TEST: ";
   b->print_board();
   board = *b;
  }

我试图在调用函数后使实际的板引用等于新板。 Board是一个抽象类,get_board()返回一个指向Board的指针,但它实际上是一个具有额外属性的board的子类。但是,在调用移动功能后,电路板与移动电话之前的电路板相同。是否可以将子类分配给指向抽象超类的指针,同时修改实际值?切片问题似乎正在发生。

1 个答案:

答案 0 :(得分:0)

我会使用Board*指针而不是Board&引用,特别是因为涉及子类:

void Player::move(Board **board, Solver &solver)
{ 
   Position *best = solver.find_best_move(*board); 
   cout << "Score: " << best->get_score() << endl; 
   *board = best->get_board(); 
   cout << "Board: "; 
   (*board)->print_board(); 
} 

Player p;
Solver solver;
Board *b = ...;
p.move(&b, solver);

或者:

void Player::move(Board* &board, Solver &solver)
{ 
   Position *best = solver.find_best_move(board); 
   cout << "Score: " << best->get_score() << endl; 
   board = best->get_board(); 
   cout << "Board: "; 
   board->print_board(); 
} 

Player p;
Solver solver;
Board *b = ...;
p.move(b, solver);