Creation of an object in C++

一曲冷凌霜 提交于 2019-12-08 14:09:30

问题


Isn't

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

supposed to work in C++?

I am getting:

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

Whats wrong with that line of code?


This works in Java, right?

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


回答1:


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;

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.

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




回答2:


new A() returns a pointer A*. You can write

A a = A();

which creates a temporary instance with the default constructor and then calls the copy constructor for a or even better:

A a;

which just creates a with the default constructor. Or, if you want a pointer, you can write

A* a = new A();

which allows you more flexibility but more responsibility.




回答3:


The keyword new is used when you want to instantiate a pointer to an object:

A* a = new A();

It gets allocated onto the heap.. while when you don't have a pointer but just a real object you use simply

A a;

This declares the object and instantiate it onto the stack (so it will be alive just inside the call)




回答4:


You need A* a= new A();

new A(); creates and constructs an object of type A and puts it on the heap. It returns a pointer of that type.

In other words new returns the address of where the object was put on the heap, and A* is a type that holds an address for an object of type A

Anytime you use the heap with new you need to call an associated delete on the address.




回答5:


new gets you a pointer to the created object, therefore:

A *a = new A();



回答6:


First, new returns a pointer, so you need to declare the a's type as 'A*'. Second, unlike Java, you don't need parenthesis after A:

A* a = new A;



来源:https://stackoverflow.com/questions/2647660/creation-of-an-object-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!