gpt4 book ai didi

c++ - 子对象上的 ostream 获取其父对象的 ostream

转载 作者:行者123 更新时间:2023-11-28 06:15:52 24 4
gpt4 key购买 nike

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

分配:

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;
}
}

我有两个类(class)

图:

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:

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 );
}

问题是,如果我尝试从板上找出 FreeSpot 对象,它需要 Figure 的 ostream。

cout << board[i][j];

我做错了什么吗?非常感谢。

最佳答案

那是因为 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;
}

关于c++ - 子对象上的 ostream 获取其父对象的 ostream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30337806/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com