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;
};
这篇关于“不完整类型"在具有与类本身相同类型的成员的类中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:“不完整类型"在具有与类本身相同类型的成员的类中
基础教程推荐
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01