'新'操作员理解

时间:2017-07-19 16:50:42

标签: c++

需要详细说明新的' C ++中的运算符。 有人可以解释为什么以下有效:

int *n = new int(10);  // initialize the pointer to integer as '10'
cout << *n;            // o/p -> 10

但这不起作用?

int p = new int (10);  // error: invalid conversion from 'int*' to 'int' [-fpermissive]

2 个答案:

答案 0 :(得分:0)

new运算符与指针一起使用,而不是int类型 所以

   int x = 5;
   int *p = &x;
   int *q = new int(4);

并且您可以将它与类struct一起使用,依此类推但不是纯类型 我的意思是只是int char ..等等。

这是新声明:

  void* operator new[] (std::size_t size);
  void* operator new[] (std::size_t size, const std::nothrow_t& nothrow_value) noexcept;
  void* operator new[] (std::size_t size, void* ptr) noexcept;

正如你所看到的那样返回指针类型为void所以你不能用c / c ++ 写

  int x = p; // error : invalid conversion from 'int*' to 'int'

与你所做的相同。

答案 1 :(得分:0)

从错误消息本身可以看出这一点。 错误:来自&#39; int *&#39;的转换无效到&#39; int&#39;

自&#34; new&#34;如果成功则返回指针。这就是当您尝试将其分配给int时出现错误的原因。