子对象的Ostream获取父对象的Ostream
ostream on child object takes ostream of his parent
我有一个满是小雕像的游戏板。
分配: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 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对象,它会占用图的流。
cout << board[i][j];
我做错了什么吗?非常感谢。
这是因为对象切片。
board
是Figure
的容器。当你这样做的时候:
FreeSpot F( i,j );
board[i][j] = F;
你把一个FreeSpot挤进一个Figure。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;
}
标题>相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- CMake-按正确顺序将项目与C运行时对象文件链接
- 空基优化子对象的地址
- 为什么常量词在重载运算符中不与 ostream 对象一起使用<<?
- 为什么重载运算符上的异常说明符'<<'不适用于任何 std::ostream 对象,但对库中定义的运算符不起作用?
- C++ ostream 从对象数组返回数据
- 如何跟踪写入std :: Ostream对象的字节数
- 使用 std::ostream 方法将格式化文本输出到 std::string 对象
- 如何获取您放入 ostream 对象中的最后一个字符
- 检查是否已写入给定的 ostream 对象
- 使用指针数组中的对象调用重载的友元 ostream 插入运算符将返回内存地址
- 重载 std::ostream 运算符<<未调用,stream 获取变量地址而不是对象
- 使用boost::python时,将python.io对象转换为std::ostream
- 对象文件中的ostream操作符发生了什么?
- 为什么即使我没有使用 ostream 对象,ostream 的 put 指针也会被修改
- 如何传递ostream对象
- 我可以使用FILE*来初始化c++ ostream对象吗?
- 关于临时ostream对象的c++问题
- 子对象的Ostream获取父对象的Ostream