[英]Creation of an object in C++
Isn't 是不是
A a = new A(); // A is a class name
supposed to work in C++? 应该在C ++中工作?
I am getting: 我正进入(状态:
conversion from 'A*' to non-scalar type 'A' requested
从“ A *”到非标量类型“ A”的转换请求
Whats wrong with that line of code? 那行代码怎么了?
This works in Java, right? 这在Java中有效,对吧?
Also, what is the correct way to create a new object of type A
in C++, then? 另外,在C ++中创建
A
类型新对象的正确方法是什么呢?
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. 但是,与Java不同,通常不需要使用C ++动态创建对象,因此应尽可能避免这样做。 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?
您使用的是哪本C ++教科书,但没有涵盖该书?
new A()
returns a pointer A*
. new A()
返回指针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: 它会使用默认构造函数创建一个临时实例,然后调用copy构造函数以获得更好的效果:
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. 这可以让您具有更大的灵活性,但又可以承担更多责任。
The keyword new
is used when you want to instantiate a pointer to an object: 当您要实例化指向对象的指针时,使用关键字
new
:
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) 这将声明该对象并将其实例化到堆栈上(这样它就可以在调用内部保持活动状态)
You need A* a= new A();
您需要
A* a= new A();
new A();
creates and constructs an object of type A
and puts it on the heap. 创建并构造类型为
A
的对象,并将其放在堆上。 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
换句话说,
new
返回对象在堆上的放置地址,而A*
是保存类型A
对象地址的类型A
Anytime you use the heap with new
you need to call an associated delete
on the address. 每当您将堆与
new
一起使用时,您都需要在地址上调用关联的delete
。
new
获取指向创建对象的指针,因此:
A *a = new A();
First, new returns a pointer, so you need to declare the a's type as 'A*'. 首先,new返回一个指针,因此您需要将a的类型声明为“ A *”。 Second, unlike Java, you don't need parenthesis after A:
其次,与Java不同,您不需要在A之后加上括号:
A* a = new A; A * a =新A;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.