“不完整类型"在具有与类本身相同类型的成员的类中

quot;Incomplete typequot; in class which has a member of the same type of the class itself(“不完整类型在具有与类本身相同类型的成员的类中)

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

问题描述

我有一个类应该有同一个类的私有成员,例如:

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;
};

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

本文标题为:“不完整类型"在具有与类本身相同类型的成员的类中

基础教程推荐