The * in C++ Initialisations
Possible Duplicate:
The Definitive C++ Book Guide and List
I'm new to C++ and have been playing around witha few examples, I was just wondering what the * meant when initialising a class.
Normally in AS3 I would do this:
MyClass myClass = new MyClass
But I have seen this in c++
MyClass *myClass = new MyClass
What is the star for, I;ve seen it used sometimes and not others.
Thanks!
The asterisk in C++ means many things depending on its place in the program. In this specific instance, it modifies the meaning of myClass
to be a pointer to an instance of MyClass
, rather than an instance of MyClass
.
The difference between the two is that the lifetime of an instance ends when it goes out of scope, while an instance that you allocate and reference through a pointer remains valid even after a pointer goes out of scope.
It is valid to have a declaration like this:
MyClass myClass; // no "new"
In this case, it is not necessary to use new
, but the instance's life time is tied to the scope of the variable myClass
.
An asterisk stand for a pointer
. A pointer is a memory adress. When you write MyClass *myClass
, you create a pointer to the beginning of the bits range where your new MyClass is created.
Creating an object with new
, you become responsible of it life cycle. YOU will need to delete it when you dont need them anymore, whereas creating MyClass myClass;
will be destroy when exiting the scope where you create it. You still can access myClass memory adress even when written this way, using &
operator.
If you need more explaination, try to get one of those books.
链接地址: http://www.djcxy.com/p/85466.html上一篇: 整数到布尔奇怪的语法
下一篇: *在C ++初始化中