1. 程式人生 > >[C++] Object i = Object(0)和Object* i = new Object(0)的區別

[C++] Object i = Object(0)和Object* i = new Object(0)的區別

pil nod 正常 -cp his tor ddr pretty 例子

C/C++裏指針通常是指向一個對象的,所以不能指向某一變量(Object i,i為某個變量),不過在Java中所有變量都是對象

舉個例子:

int a=1;

int *p=a;

報錯:invalid conversion from ‘int‘ to ‘ int* ‘;

int *a = new int(1);

int *p=a;

正常運行!

再來看一個較為復雜一點的例子(將一個二叉鏈表的結點類作為我們的Object):

template<class T>

struct BTNode
{
  T data;
  BTNode *left,*right;
  BTNode(const T& item=T(),BTNode *lptr=NULL,BTNode *rptr=NULL):data(item),left(lptr),right(rptr){}
};

int main()
{
  BTNode<char> a=BTNode<char>(‘D‘,NULL,NULL);
  BTNode<char> *ap=a;
  return 0;
}

同樣地會報錯:cannot convert ‘BTNode<char>‘ to ‘BTNode<char>*‘ int initialization

而這樣做就可以了:

int main()
{
  BTNode<char> *a=new BTNode<char>(‘D‘,NULL,NULL);
  BTNode<char> *ap=a;
  return 0;
}

以上問題的原因都是因為指針指向了某一變量而不是對象,而用new Object()則是生成的一個對象並將地址給=前面的指針

再來看StackOverFlow裏的一個例子:

struct Foo {
  int value; // 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 keyword.  It says that it can only be EXPLICITLY created from a double
};


Foo i = Foo(0);

the above creates an int literal, then constructs Foo i with it using the Foo(int v) constructor, then copy-constructs Foo i from it. However, the standard allows the compiler to "elide" (skip) the copy constructor, and instead just construct Foo i directly 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, then constructs it with the integer literal 0. It then returns the address of this Foo object, which is then used to initialize the pointer Foo* i.

[C++] Object i = Object(0)和Object* i = new Object(0)的區別