2012-10-05 38 views
1

我正在玩指針和動態內存,因爲我試圖學習C++,並且在編譯時我一直收到這個錯誤。使用動態分配的內存(指針)

error C2678: binary '>>' : no operator found which takes a left-hand operand of type 'std::istream' (or there is no acceptable conversion) 

我的代碼如下:

int * ageP;  
ageP = new (nothrow) int; 

if (ageP == 0) 
{ 
    cout << "Error: memory could not be allocated"; 
} 
else 
{ 
    cout<<"What is your age?"<<endl; 
    cin>> ageP;      <--this is the error line 
    youDoneIt(ageP);            
    delete ageP; 
} 

任何想法?先謝謝您的幫助。

回答

2

問題是你需要一個int的引用,而不是int *。例如

int ageP; 
cin >> ageP; 

因此,刪除也是不必要的,因爲你不會使用指針。

希望它有幫助。

+2

謝謝 - 真的。我正在編輯這個名字......現在我有天賦了。 –

2

John從本質上說是正確的,您的問題是提供一個指針,指向哪裏需要引用。

但是,由於您試圖瞭解動態分配,因此使用自動變量不是一個好的解決方案。相反,您可以使用*解引用運算符從指針創建引用。

int* ageP = new (nothrow) int; 
std::cout << "What is your age?" << std::endl; 
std::cin >> *ageP;           
delete ageP; 
6

你有指針ageP指向的內存,這個調用分配:ageP = new int;您可以通過取消引用指針訪問該內存(使用dereference operator即:*ageP):

MEMORY 
|  | 
|--------| 
| ageP | - - - 
|--------|  | 
| ... |  | 
|--------|  | 
| *ageP | < - - 
|--------| 
|  | 

然後它是一樣的,你會使用類型爲int的變量,所以之前當你使用類型爲int的變量時,像這樣:

int age; 
cin >> age; 

現在它將成爲:

int *ageP = new int; 
cin >> *ageP; 
+0

最後一行應該說'ageP'。否則好的解決方案和很好的解釋 –

+0

是的,這是錯字:)順便說一句,我的回答沒有提及*「stack versus heap」*或*「automatic vs. dynamic storage duration」*,因爲我想保持簡單。 – LihO

+0

謝謝!現在它變得更有意義。 – PStokes