C++:一个类可以有它自己类型的对象吗? [英] C++: Can a class has an object of it's own type?

查看:82
本文介绍了C++:一个类可以有它自己类型的对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用 C++ 解决康威的生命游戏.所以根据我的设计,我有一个包含 8 个邻居列表的单元格类,它本身是一个单元格类型的对象.这样做可以吗.代码看起来像这样

I am trying to solve the Conway's game of life in c++. So according to my design, I have a cell class which contains a list of 8 neighbours, which itself is an object of type cell. Is it ok to do that. The code looks like this

class Cell {
private:
  int position_row_;
  int position_colm_;
  std::shared_ptr<State> state_;

  std::vector<Cell> neighbours_;
};

现在,另一个困扰我的问题是,这是一种什么样的关系.在设计时,我认为它是聚合";但现在我不这么认为.有人可以澄清一下吗?

Now, the other question that is bugging me is, what type of relationship is it. While designing i thought of it to be 'Aggregation'; but now i don't think so. Can someone please clarify?

推荐答案

std::vector<Cell> neighbours;

您正在存储邻居的副本.如果任何邻居的状态发生变化怎么办?您是否需要将该更改反映到向量中?如果是,最好存储指向邻居的指针:

You are storing copy of neighbours. What if state of any neighbour changes? Do you need that change to be reflected into the vector? If yes, better store the pointers to the neighbours:

std::vector<std::shared_ptr<Cell>> neighbours;

这篇关于C++:一个类可以有它自己类型的对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆