用C ++创建对象 [英] Creation of an object in C++

查看:96
本文介绍了用C ++创建对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不是

 A a = new A();   // A is a class name

是否应该在C ++中工作?

supposed to work in C++?

我得到了:

从"A *"到非标量的转换 输入要求的"A"

conversion from 'A*' to non-scalar type 'A' requested

那行代码怎么了?

这在Java中有效,对吧?

This works in Java, right?

然后,用C ++创建类型为A的新对象的正确方法是什么?

Also, what is the correct way to create a new object of type A in C++, then?

推荐答案

不,不是.新操作将返回指向新创建的对象的指针,因此您需要:

No, it isn't. The new operation returns a pointer to the newly created object, so you need:

A * a = new A();

您还需要在代码中的其他位置管理对象的删除:

You will also need to manage the deletion of the object somewhere else in your code:

delete a;

但是,与Java不同,通常不需要使用C ++动态创建对象,并且在任何可能的情况下都应避免这样做.除了上述内容,您还可以简单地说:

However, unlike Java, there is normally no need to create objects dynamically in C++, and whenever possible you should avoid doing so. Instead of the above, you could simply say:

A a;

,编译器将为您管理对象的生存期.

and the compiler will manage the object lifetime for you.

这是非常基础的东西.您使用的是哪本C ++教科书,但没有涵盖?

This is extremely basic stuff. Which C++ text book are you using which doesn't cover it?

这篇关于用C ++创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆