使用动态分配的内存(指针)

PSt*_*kes 1 c++ io pointers dynamic-memory-allocation visual-c++

当我正在尝试学习C++时,我正在玩指针和动态内存,并且在编译时我不断收到此错误.

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

我的代码如下:

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;
}
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?在此先感谢您的帮助.

Lih*_*ihO 6

你有指针ageP指向的内存,这个调用分配:ageP = new int;您可以通过取消引用指针(通过使用IE浏览器访问该存储器引用操作:*ageP):

  MEMORY
|        |
|--------|
|  ageP  | - - - 
|--------|      |
|  ...   |      |
|--------|      |
| *ageP  | < - -
|--------|
|        |
Run Code Online (Sandbox Code Playgroud)

然后就像你使用变量类型一样int,所以在你使用int类似变量之前:

int age;
cin >> age;
Run Code Online (Sandbox Code Playgroud)

现在它将成为:

int *ageP = new int;
cin >> *ageP;
Run Code Online (Sandbox Code Playgroud)