是否可以拥有Car类型的对象,其中包含Car的向量? [英] Is it to possible to have an object of type Car, which contains a vector of Car?
本文介绍了是否可以拥有Car类型的对象,其中包含Car的向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果是这样,这不会导致任何问题吗?
我想如果可能的话,构造函数应该将向量设置为null;否则它会创造一个无限循环?
我认为这是可能的,但我不确定。对不起,问题可能听起来很愚蠢。
If so, wouldn't that cause any problem?
I guess if it is at all possible, the constructor should set the vector to null; otherwise it will create an infinite loop?
I think it is possible, but I am not sure. Sorry, the question may sound dumb.
推荐答案
这绝对是可能的,但在实施的充分白痴条件下,无限循环也是可能的: - )。如果你以最简单的方式做到这一点,它将立即起作用,原因很简单:在构造时,向量包含零元素:
It is absolutely possible, but "infinite loop" is also possible, under the condition of the sufficient idiocy of the implementation :-). If you do it in the simplest possible way, it will immediately work, by a very simple reason: at the moment of construction, the vector contains zero elements:
class VectorOfElementsWithVector {
public:
void Add(VectorOfElementsWithVector &element) { m_vector.push_back(element); }
private:
std::vector<VectorOfElementsWithVector> m_vector;
};
//...
// no problem to add elements to the vector:
VectorOfElementsWithVector container, element;
container.Add(element);
此外,您可以对阵列执行相同操作,但之后您将需要使用堆。只有当你试图构造一个类似的类的实例试图确保每个向量在构造函数中至少有一个元素时,它才会导致无限的递归。
这篇关于是否可以拥有Car类型的对象,其中包含Car的向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文