C + + pointers are usually pointing to an object, so they cannot point to a variable (object i,i is a variable), but all variables in Java are objects
As an example:
int a=1;
int *p=a;
Error: Invalid conversion from ' int ' to ' int* ';
int *a = new int (1);
int *p=a;
Normal operation!
Let's look at a more complicated example (the node class of a binary list as our object):
Template<class t>
struct Btnode
{
T data;
Btnode *left,*right;
Btnode (const t& item=t (), Btnode *lptr=null,btnode *rptr=null):d ATA (item), left (LPTR), right (Rptr) {}
};
int main ()
{
Btnode<char> a=btnode<char> (' D ', null,null);
Btnode<char> *ap=a;
return 0;
}
Same error: Cannot convert ' btnode<char> ' to ' btnode<char>* ' int initialization
And that's all you can do:
int main ()
{
btnode<char> *a=new btnode<char> (' D ', null,null);
Btnode<char> *ap=a;
return 0;
}
The problem is because the pointer points to a variable instead of an object, and the new object () is the resulting object and gives the address = previous pointer
Take another look at the example in StackOverflow:
struct Foo { IntValue; Foo stores an int, called value Foo(Int V): value (v {};//Foo can be constructed (created) from an int explicit foo (double D value (d {};//Foo can be constructed (created) from a double //^^ ^ Note that K Eyword. It says that it can is explicitly created from a double};
Foo i = Foo(0);
The above creates an int literal and then constructs with Foo i it using Foo(int v) the constructor and then Copy-constructs Foo i From it. However, the standard allows the compiler to "Elide" (skip) the copy constructor, and instead just construct directl Foo i Y from the int literal 0 .
Foo* i = new Foo(0);
This goes to the free store (typically implemented and called the heap), gets ahold of enough memory to store a Foo , the n constructs it with the integer literal 0. It then returns the address of this Foo object, which are then used to initialize the pointer Foo* i .
[C + +] The difference between object i = Object (0) and object* i = new Object (0)