C++ Pointers and Object Instantiation

杀马特。学长 韩版系。学妹 提交于 2019-12-24 09:55:39

问题


This works:

MyObject *o;
o = new MyObject();

And this does not:

MyObject o = new MyObject();

Why?


回答1:


The keyword new returns a pointer. It must be assigned to a pointer of an object.

This would also work:

MyObject o = MyObject();

EDIT:

As Seth commented, the above is equivalent to:

MyObject o;

The default constructor (i.e. without parameters) is called if no constructor is given.




回答2:


Because they're not equivalent. Try:

 MyObject* o = new MyObject();



回答3:


new MyObject() returns a pointer to an object of type MyObject. So really you are trying to assign an object MyObject* (yes, a pointer can be considered an object, too). Thus, you have to declare a variable of MyObject* or something compatible like std::shared_ptr<MyObject>.

The proper initialisation is

// in C++03
MyObject* o(new MyObject());

// in C++11
MyObject* o {new MyObject()};

While the assignment

MyObject* o = new MyObject();

is valid as well.



来源:https://stackoverflow.com/questions/10156789/c-pointers-and-object-instantiation

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