【问题标题】:working with dynamically allocated memory (pointer)使用动态分配的内存(指针)
【发布时间】:2012-10-05 18:00:58
【问题描述】:

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

有什么想法吗?提前感谢您的帮助。

【问题讨论】:

    标签: c++ visual-c++ pointers io dynamic-memory-allocation


    【解决方案1】:

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

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

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

    int age;
    cin >> age;
    

    现在它会变成:

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

    【讨论】:

    • 最后一行应该是ageP。否则很好的解决方案和很好的解释。
    • 是的,那是错字 :) 顺便说一句,我的回答没有说​​明 "stack vs. heap""automatic vs. dynamic storage duration " 因为我想保持简单。
    • 谢谢!现在更有意义了。
    【解决方案2】:

    John 基本上是正确的,您的问题是提供了一个需要引用的指针。

    但是,由于您正在尝试了解动态分配,因此使用自动变量并不是一个好的解决方案。相反,您可以使用 * 取消引用运算符从指针创建引用。

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

    【讨论】:

      【解决方案3】:

      问题是您需要对 int 的引用,而不是 int*。比如

      int ageP;
      cin >> ageP;
      

      因此,删除也是不必要的,因为您不会使用指针。

      希望对你有帮助。

      【讨论】:

      • 谢谢 - 真的。我正在编辑名字......现在我有天赋了。
      猜你喜欢
      • 2019-07-12
      • 2015-02-05
      • 2020-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-24
      • 2013-10-04
      相关资源
      最近更新 更多