“不完整类型"在类中具有与类本身相同类型的成员 [英] "Incomplete type" in class which has a member of the same type of the class itself

查看:91
本文介绍了“不完整类型"在类中具有与类本身相同类型的成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个班级,应该有一个属于同一班级的私人成员,例如:

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

推荐答案

在声明成员时,您仍在定义 A类,因此类型A仍为未定义.

At the time you declare your member, you are still defining the A class, so the type A is still undefined.

但是,当您编写A*时,编译器已经知道A代表类名,因此,定义了指向A的指针.这就是为什么您可以将指针嵌入要定义的类型的原因.

However, when you write A*, the compiler already knows that A stands for a class name, and so the type "pointer to A" is defined. That's why you can embed a pointer to the type your are defining.

相同的逻辑也适用于其他类型,因此,如果您只写:

The same logic applies also for other types, so if you just write:

class Foo;

您声明了Foo类,但从未定义.您可以编写:

You declare the class Foo, but you never define it. You can write:

Foo* foo;

但不是:

Foo foo;

另一方面,如果编译器允许递归定义,则您希望类型为A的内存结构是什么?

On another hand, what memory structure would you expect for your type A if the compiler allowed a recursive definition ?

但是,有时在逻辑上有效的是具有某种以某种方式引用同一类型的另一个实例的类型.人们通常使用指针来实现甚至更好:智能指针(例如boost::shared_ptr),以避免不得不手动删除.

However, its sometimes logically valid to have a type that somehow refer to another instance of the same type. People usually use pointers for that or even better: smart pointers (like boost::shared_ptr) to avoid having to deal with manual deletion.

类似的东西:

class A
{
  private:
    boost::shared_ptr<A> member;
};

这篇关于“不完整类型"在类中具有与类本身相同类型的成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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