需要C++中'new'運算符的詳細解釋。 有人可以解釋爲什麼以下工作:'new'操作符理解
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]
需要C++中'new'運算符的詳細解釋。 有人可以解釋爲什麼以下工作:'new'操作符理解
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]
的指針採用了新的運營商,不是int類型 所以
int x = 5;
int *p = &x;
int *q = new int(4);
,你可以使用類結構等,但不是單純的使用它,類型 我的意思只是INT焦炭等..
這是新的聲明:
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'
這是一樣的,你做了什麼。
這是從錯誤消息本身..很明顯 錯誤:從「詮釋*」到「廉政」
由於「新」返回一個指針,如果它是成功無效的轉換。這就是爲什麼當你試圖將它分配給一個int時你會得到一個錯誤。
你爲什麼期望第二個工作? 'new'返回一個指針。 – NathanOliver
重複? https://stackoverflow.com/questions/2726356/the-new-operator-in-c-pointer-question – Twtheo
[The Definitive C++ Book Guide and List](https://stackoverflow.com/questions/388242/the- definitive-c-book-guide-and-list) – molbdnilo