C++: Can a class has an object of it's own type?

情到浓时终转凉″ 提交于 2021-01-05 04:45:33

问题


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?


回答1:


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;



回答2:


A class cannot include itself as a data member class C { C c; }; for two reasons:

  1. When you try to define the data member the class is still an incomplete type.
  2. You are creating an endless chain of objects which would require infinite memory.

A class can contain a vector of itself class C { std::vector<C> vec; }; because, like a pointer, a vector declaration only requires that data type has been declared - not defined.

Your code will compile and run but you said your intent was for aggregation which isn't the case:

  • Your code std::vector<Cell> neighbours; is a case of composition because the objects in the vector are owned by the Cell object.
  • Using pointers to other Cell objects std::vector<Cell*> neighbours; would be a case of aggregation because the Cell object would use the objects in the vector but not own them.



回答3:


This is considered to be Reflexive Association. Because it is satisfying following conditions with having its own type has a member variable

The associated object (member) is otherwise unrelated to the object (class)
The associated object (member) can belong to more than one object (class) at a time
The associated object (member) does not have its existence managed by the object (class)

This can lead to a chain of associations The associated object (member) may or may not know about the existence of the object (class)



来源:https://stackoverflow.com/questions/26947733/c-can-a-class-has-an-object-of-its-own-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!