在 C++ 中,如何在没有动态分配(即 NEW)的情况下将对象初始化为对象内部的指针?
例如:
class A{
int b;
A *a1;
A *a2;
A(int c):b(c), a1(c), a2(c) {}
}
我认为这就是方法,但它无法编译。 有没有办法做到这一点,或者是否有必要始终使用动态分配? 谢谢
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以简单地将指针初始化为 null。
(请注意,如果它抱怨未定义 NULL,
#include>)
或者根本不初始化它们。
You could simply initialize the pointers to null.
(Note that if it complains about NULL not being defined,
#include <cstddef
>)Or not initialize them at all.
目前还不清楚你想做什么,但你当然可以做到:
你可以这样称呼:
小心点。如果
m1
或m2
在m3
之前超出范围,则m3
将保留指向随机的指针垃圾。It's not clear what you're trying to do, but you certainly can do it:
Which you can call like this:
Just be careful. If
m1
orm2
go out of scope beforem3
, thenm3
will be left with pointers that point to random garbage.如果您不想像这样初始化指向
nullptr
(NULL
或0
pre-C++11)的指针:那么指针指向的对象必须存在于某个外部作用域中,这样它的生存时间至少与包含指针的对象一样长,否则您必须使用 new。
您可以接受
A*
将指针设置为:(您不能为此使用引用,因为这将使
A
成为A 的要求
,这是一个不可能满足的条件。不过,您可以创建一个接受引用的附加构造函数。)在您的示例中,您尝试使用
int
来初始化一个指针,但它不会工作。另外,如果您在示例中创建一个对象(通过 new 或其他方式),您将耗尽内存,因为您分配的每个A
都会再分配两个A
并且该循环将继续,直到内存耗尽。If you don't want to initialise the pointers to
nullptr
(NULL
or0
pre-C++11) like this:then either the object you make the pointer point to has to exist in some outer scope so that it will live at least as long as the object that contains the pointer, or you have to use
new
.You could accept an
A*
to set the pointers to:(You can't use a reference for this because that would make an
A
a requirement for anA
, an impossible condition to satisfy. You could make an additional constructor that accepted a reference though.)In your example, you are trying to use an
int
to initialise a pointer which won't work. Also, if you create an object in your example (vianew
or whatever), you will run out of memory because eachA
you allocate will allocate two moreA
s and that cycle will continue until you run out of memory.