gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:22:56 25 4
gpt4 key购买 nike

我在尝试学习 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;
}

有什么想法吗?预先感谢您的帮助。

最佳答案

您有指向内存的指针 ageP,通过此调用分配:ageP = new int; 您可以通过取消引用指针来访问此内存(即通过使用dereference operator : *ageP):

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

然后它就像您将使用 int 类型的变量一样,所以之前当您像这样使用 int 类型的变量时:

int age;
cin >> age;

现在它将变成:

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

关于c++ - 使用动态分配的内存(指针),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12751644/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com