“Incomplete type” in class which has a member of t

2019-01-03 00:03发布

I have a class that should have a private member of the same class, something like:

class A {
    private:
        A member;
}

But it tells me that member is an incomplete type. Why? It doesn't tell me incomplete type if I use a pointer, but I'd rather not use a pointer. Any help is appreciated

8条回答
我想做一个坏孩纸
2楼-- · 2019-01-03 00:11

How can an instance of class A also contain another instance of class A?

It can hold a pointer to A if you want.

查看更多
唯我独甜
3楼-- · 2019-01-03 00:15

A is "incomplete" until the end of its definition (though this does not include the bodies of member functions).

One of the reasons for this is that, until the definition ends, there is no way to know how large A is (which depends on the sum of sizes of members, plus a few other things). Your code is a great example of that: your type A is defined by the size of type A.

Clearly, an object of type A may not contain a member object that is also of type A.

You'll have to store a pointer or a reference; wanting to store either is possibly suspect.

查看更多
劳资没心,怎么记你
4楼-- · 2019-01-03 00:15

You cannot include A within A. If you were able to do that, and you declared, for example, A a;, you would need to refer to a.member.member.member... infinitely. You don't have that much RAM available.

查看更多
闹够了就滚
5楼-- · 2019-01-03 00:15

The problem happens when the compiler comes across an object of A in code. The compiler will rub its hand and set out make an object of A. While doing that it will see that A has a member which is again of type A. So for completing the instantiation of A it now has to instantiate another A ,and in doing so it has to instantiate another A and so forth. You can see it will end up in a recursion with no bound. Hence this is not allowed. Compiler makes sure it knows all types and memory requirement of all members before it starts instantiating an object of a class.

查看更多
姐就是有狂的资本
6楼-- · 2019-01-03 00:16

A simple way to understand the reason behind class A being incomplete is to try to look at it from compiler's perspective.

Among other things, the compiler must be able to compute the size of A object. Knowing the size is a very basic requirement that shows up in many contexts, such as allocating space in automatic memory, calling operator new, and evaluating sizeof(A). However, computing the size of A requires knowing the size of A, because a is a member of A. This leads to infinite recursion.

Compiler's way of dealing with this problem is to consider A incomplete until its definition is fully known. You are allowed to declare pointers and references to incomplete class, but you are not allowed to declare values.

查看更多
\"骚年 ilove
7楼-- · 2019-01-03 00:20

This is a working example of what you are trying to achieve:

class A {
public:
    A() : a(new A()) {}
    ~A() { delete a; a = nullptr; }
private:
    A* a;
};

A a;

Happy Stack Overflow!

查看更多
登录 后发表回答