类中不完整的类型

类中不完整的类型

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

问题描述

我有一个类,应该有一个私人成员的同一个类。所以像这样 -

I have a class that should have a private member of the same class. So like this -

class A{
    private:
        A member;
}

但它告诉我,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;

另一方面,你期望的类型是什么内存结构 / code>如果编译器允许递归定义?

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

这篇关于类中不完整的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 19:02