[英]working with dynamically allocated memory (pointer)
I was playing around with pointers and dynamic memory as I'm trying to learn C++ and I keep getting this error when I compile. 在尝试学习C ++的过程中,我一直在使用指针和动态内存,并且在编译时不断出现此错误。
error C2678: binary '>>' : no operator found which takes a left-hand operand of type 'std::istream' (or there is no acceptable conversion)
My code is as follows: 我的代码如下:
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;
}
Any ideas? 有任何想法吗? Thanks in advance for the help.
先谢谢您的帮助。
You have pointer ageP
that points to memory, allocated by this call: ageP = new int;
您有指针
ageP
指向此调用分配的内存: ageP = new int;
You can access this memory by dereferencing your pointer (ie by using the dereference operator : *ageP
): 您可以通过解除对指针的引用来访问此内存(即,使用解除引用运算符 :
*ageP
):
MEMORY
| |
|--------|
| ageP | - - -
|--------| |
| ... | |
|--------| |
| *ageP | < - -
|--------|
| |
And then it's same like you would be working with variable of type int
, so before when you worked with variable of type int
like this: 然后就像使用
int
类型的变量一样,所以在使用int
类型的变量之前是这样的:
int age;
cin >> age;
now it will become: 现在它将变为:
int *ageP = new int;
cin >> *ageP;
The problem is that you need a reference to an int, not an int*. 问题是您需要引用一个int,而不是int *。 For instance
例如
int ageP;
cin >> ageP;
Thus, the delete is also unnecessary as you won't be utilizing a pointer. 因此,删除也是不必要的,因为您将不会使用指针。
Hope it helps. 希望能帮助到你。
John is essentially correct that your problem is supplying a pointer where a reference is expected. John本质上是正确的,您的问题是在需要引用的地方提供了一个指针。
However, since you're trying to learn about dynamic allocation, using an automatic variable is not a good solution. 但是,由于您尝试学习动态分配,因此使用自动变量不是一个好的解决方案。 Instead, you can create a reference from a pointer using the
*
dereference operator. 相反,您可以使用
*
取消引用运算符从指针创建引用。
int* ageP = new (nothrow) int;
std::cout << "What is your age?" << std::endl;
std::cin >> *ageP;
delete ageP;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.