子对象上的ostream占用了他父母的ostream

时间:2015-05-19 23:24:48

标签: c++ polymorphism ostream

我有一个装满小雕像的游戏板。

分配:

implicit class MathExtensions(val obj: scala.math.type) {
    def min(x: Money, y: Money): Money = ???
}

我有两个课程

图:

board = new Figure*[boardSize];
for (int i = 0; i < boardSize; ++i) board[i] = new Figure[boardSize];

for (int i = 0; i < boardSize; ++i)
{
    for (int j = 0; j < boardSize; ++j)
    {
        FreeSpot F( i,j );
        board[i][j] = F;
    }
}

作为一个孩子,FreeSpot:

class Figure {
  public:
        Figure          ( );
        ~Figure         ( void );

        virtual void  print ( ostream & os ) const;
        friend ostream  & operator << ( ostream & os, const Figure & F );

        int positionX;
        int positionY;
  private:
};

void Figure::print ( ostream & os ) const {
   os << "[" << positionY << "," << positionX << "]";
 }

ostream  & operator << ( ostream & os, const Figure & f ) {
   f . print ( os );
   return ( os );
 }

问题是,如果我尝试从板上传播FreeSpot对象,那就需要ostream图。

class FreeSpot: public Figure {
  public:

        FreeSpot            ( int, int );
        ~FreeSpot           ( void );

        virtual void print ( ostream & os ) const;
        friend ostream & operator << ( ostream & os, const FreeSpot & F );

        char shape;
  private:
};

void FreeSpot::print ( ostream & os ) const {
   os << "[" << positionY << shape << positionX << "]";
 }

 ostream  & operator << ( ostream & os, const FreeSpot & f ) {
   f . print ( os );
   return ( os );
 }

我做错了吗? 非常感谢。

1 个答案:

答案 0 :(得分:1)

那是因为object slicing

boardFigure的容器。所以当你这样做时:

    FreeSpot F( i,j );
    board[i][j] = F;

你将FreeSpot压缩成图。 F的Figure子对象将被复制到棋盘中,但FreeSpot特定属性将丢失。因此结果将是Figure

这就是为什么尽管你打电话给多态print(),你最终只打印数字。

解决方案

你必须使board [] []成为指向元素的指针数组。或者更好:shared_ptr。你不会再受到切片的困扰。记忆管理会更容易:

const int boardSize=8; 
vector< vector< shared_ptr<Figure> > > board(boardSize, vector<shared_ptr<Figure>>(boardSize));

for (int i = 0; i < boardSize; ++i) {
    for (int j = 0; j < boardSize; ++j) {
        board[i][j] = static_pointer_cast<Figure>(make_shared<FreeSpot>(i,j));
        cout << *board[i][j]<< " ";
    }
    cout<<endl; 
}