开发者

Object of same type as class

开发者 https://www.devze.com 2023-04-12 06:00 出处:网络
In c++ how do I have an object as the same type as its containing class eg: class Test { public: private:

In c++ how do I have an object as the same type as its containing class eg:

class Test
{
public:

private:
开发者_如何学编程  Test t;
};


Short answer, you can't.

You can have a pointer to an object of the same type, but not an object itself.

If you NEED to do this (i.e.) can't use a pointer, your design is probably wrong. If you can use a pointer, use it.

Some reasons:

You'd have to create the object on instantiation, that means an infinite recursive call on the constructor.

What would the sizeof() for the object be?


You can't do that, since it would require infinite recursion. (Your t would contain another t, so you'd have t.t.t.t.t.t.t.t.... ad infinitum). What you could do though is put a pointer to another object inside, e.g.

private:
   Test *t;

The problem is that when you write:

Test t;

The compiler needs to know the size of Test in order to provide sufficient storage. At the point where you wrote Test t; that size isn't known because the compiler hasn't seen the end of the definition of Test (i.e. the ; after the closing }) and thus can't determine the size of it.


That's not possible. At the max you can have a reference or pointer of the same class within it.

class Test
{
private:
  Test *t;
};

As a side note, static objects are allowed. This is because, they are not actually bound with any particular instance of class object. i.e.:

class Test
{
private:
  Test t; // error
  static Test st; // ok!
};  // define 'st' in the translation unit
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号