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

2023-08-28C/C++开发问题
1

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

问题描述

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

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

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

The End

相关推荐

无法访问 C++ std::set 中对象的非常量成员函数
Unable to access non-const member functions of objects in C++ std::set(无法访问 C++ std::set 中对象的非常量成员函数)...
2024-08-14 C/C++开发问题
17

从 lambda 构造 std::function 参数
Constructing std::function argument from lambda(从 lambda 构造 std::function 参数)...
2024-08-14 C/C++开发问题
25

STL BigInt 类实现
STL BigInt class implementation(STL BigInt 类实现)...
2024-08-14 C/C++开发问题
3

使用 std::atomic 和 std::condition_variable 同步不可靠
Sync is unreliable using std::atomic and std::condition_variable(使用 std::atomic 和 std::condition_variable 同步不可靠)...
2024-08-14 C/C++开发问题
17

在 STL 中将列表元素移动到末尾
Move list element to the end in STL(在 STL 中将列表元素移动到末尾)...
2024-08-14 C/C++开发问题
9

为什么禁止对存储在 STL 容器中的类重载 operator&amp;()?
Why is overloading operatoramp;() prohibited for classes stored in STL containers?(为什么禁止对存储在 STL 容器中的类重载 operatoramp;()?)...
2024-08-14 C/C++开发问题
6