error C2440: 'initializing' : cannot convert from 'classname *' to 'classname'
I have a class defined called extBlock.
I then make an instance of that class with this
extBlock mainBlock = new extBlock(1, 1024);
I get this error: error C2440: 'initializing' : cannot convert from 'extBlock *' to 'extBlock'
Can anyone help me with why I am getting this error.
I have seen examples online of declaring it like this with a pointer
extBlock *mainBlock = new extBlock(1, 1024);
But if I do it this way it does not let 开发者_开发百科me call the functions of mainBlock
Read up on your C++ syntax:
extBlock mainBlock(1, 1024); // create a class instance (object) on the stack
mainBlock.memberFunction(); // call a member function of a stack object
extBlock * ptrBlock = new extBlock(1, 1024); // create an object on the heap
ptrBlock->memberFunctions(); // member access through pointers has different syntax
delete ptrBlock; // must deallocate memory when you're done with a heap object
Switching from Java/C#?
In C++, to initialize an object on stack, you just need to use
extBlock mainBlock (1, 1024);
...
mainBlock.call_func(1,2,4,7,1);
The new operator creates an object on heap, and return the pointer to it. To access functions from a pointer, you need to dereference it with *:
extBlock* mainBlock = new extBlock(1,1024);
...
(*mainBlock).call_func(1,2,4,7,1);
In C and C++, a->b can be used in place of (*a).b:
mainBlock->call_func(1,2,4,7,1);
Also, C++ doesn't have Garbage Collection by default, so you need to deallocate with delete explicitly:
delete mainBlock;
This isn't C#: new extBlock returns a pointer to an extBlock, and you're trying to assign that pointer to a value type (which would be an incompatible cast).
What you want to write here is
extBlock mainBlock(1, 1024);
And the reason you couldn't call methods on the second code snippet was probably because you were using the . operator instead of the -> (arrow) operator needed to dereference a pointer.
You want this, like you had:
extBlock *mainBlock = new extBlock(1, 1024);
but then you call functions using -> instead of ., like this:
mainBlock->FunctionOnIt(...);
Don't forget to delete it when it's no longer needed.
delete mainBlock;
new returns a pointer to the allocated memory, where the constructor has initialized your object. Thus you need to use extBlock *mainBlock = new extBlock(1, 1024);. You can call the methods afterwards via mainBlock->someMethod() or (*mainBlock).someMethod().
The new keyword always assigns to a pointer. What you need to do is something like this:
extBlock *mainBlock = new extBlock(1, 1024);
mainBlock->functionName();
Since mainBlock is now a pointer, the . operator won't work anymore to reference fields or methods and the -> operator must be used in its place.
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论