C++ 中变量声明的差异

发布于 2024-08-29 19:39:24 字数 122 浏览 4 评论 0原文

Class A 
{
};

A aA* aA* a = new A() 之间有什么区别。

Class A 
{
};

What is the difference between A a , A* a and A* a = new A().

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

最冷一天 2024-09-05 19:39:25
A a;

使用默认构造函数创建位于堆栈中的 A 实例。

A *a;

只是一个指向 A 的未初始化指针。此时它实际上并不指向 A 对象,但可以。已初始化的指针(在本例中设置为 NULL)如下所示:

A *a = 0;

此处的区别在于,空指针不指向任何对象,而未初始化的指针可能指向任何地方。初始化指针是一个很好的做法,以免您发现自己想知道为什么程序会崩溃或产生不正确的结果。

同样,您不想尝试取消引用 NULL 指针或未初始化的指针。但你可以测试 NULL 指针。测试未初始化的指针会产生不确定的错误结果。它实际上可能是 != 0 但肯定不会指向您想要它指向的任何地方。确保在测试指针之前初始化指针,并在尝试取消引用指针之前测试指针。

A a = new A();

应该写成

A *a = new A();

并创建一个在堆上分配的新 A 对象。 A 对象是使用默认构造函数创建的。

如果没有为类显式编写默认构造函数,则编译器将隐式创建一个默认构造函数,尽管我不相信该标准没有指定隐式实例化对象的数据成员的状态。有关隐式默认构造函数的讨论,请参阅 Martin York 对这个 SO 问题的回复

A a;

Creates an instance of an A that lives on the stack using the default constructor.

A *a;

Is simply a uninitialized pointer to an A. It doesn't actually point to an A object at this point, but could. An initialized pointer (in this case, set to NULL) would look like so:

A *a = 0;

The difference here is that a null pointer does not point to any object while an uninitialized pointer might point anywhere. Initializing your pointers is a good practice to get into lest you find yourself wondering why your program is blowing up or yielding incorrect results.

Similarly, you don't want to attempt to dereference either a NULL pointer or an uninitialized pointer. But you can test the NULL pointer. Testing an uninitialized pointer yields undetermined and erroneous results. It may in fact be != 0 but certainly doesn't point anywhere you intend it to point. Make sure you initialize your pointers before testing them and test them before you attempt to dereference them.

A a = new A();

should be written as

A *a = new A();

and that creates a new A object that was allocated on the heap. The A object was created using the default constructor.

Where a default constructor is not explicitly written for a class, the compiler will implicitly create one though I don't believe the standard does not specify the state of data members for the object implicitly instantiated. For a discussion about implicit default constructors, see Martin York's response to this SO question.

风情万种。 2024-09-05 19:39:25

A a 声明一个名为 aA 实例

A *a 声明一个指向 A< /code> class

A *a = new A() 在堆上为 a 分配空间并调用正确的构造函数(如果没有指定构造函数,则执行默认初始化) 。

有关最后一个表单的更多信息,请参阅 http://en.wikipedia。 org/wiki/New_%28C%2B%2B%29

A a declares an instance of A named a

A *a declares a pointer to a A class

A *a = new A() allocates space for a on the heap and calls the proper constructor (if no constructor is specified, it performs default initialization).

For further information about the last form see http://en.wikipedia.org/wiki/New_%28C%2B%2B%29

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文