Conversion from 'myItem*' to non-scalar type 'myItem' requested

前端 未结 4 711
感动是毒
感动是毒 2020-12-05 17:45

I have this C++ code:

#include 
using namespace std;
struct MyItem
{
  int value;
  MyItem* nextItem;
};

int main() {
    MyItem item = new          


        
相关标签:
4条回答
  • 2020-12-05 18:22

    Try:

    MyItem * item = new MyItem;
    

    But do not forget to delete it after usage:

    delete item;
    
    0 讨论(0)
  • 2020-12-05 18:22

    First of all, this code won't compile because you forgot the semi-colons after each member variable declaration and after MyItem declaration and the keyword "struct" is typed wrong. Your code should look like this:

    struct MyItem
    {
    var value;
    MyItem* nextItem;
    };
    
    MyItem item = new MyItem;
    

    Now answering your question, this code does not work because the new operator returns a pointer to the object created (a value of type MyItem*) and you are trying to assign this pointer to a variable of type MyItem. The compiler does not allow you to do this (because the value and the variable have different types). You should store the pointer into an apropriate variable, like this:

    MyItem* item = new MyItem;
    

    In this case, you must remember to delete item to avoid memory leak once you no more need it.

    Alternatively, you can create the object in the stack without the new operator.

    MyItem item;
    

    In this case, the object ceases to exist when the function returns; you don't need to remember to delete it.

    0 讨论(0)
  • 2020-12-05 18:23

    Here is edited code with changes mentioned on the right

    struct MyItem                  // corrected spelling struct
    {
        var value;                 // added ;
        struct MyItem * nextItem;  // add "struct" and added ;
    };                             // added ;
    
    MyItem * item = new MyItem;    // added * before item
    
    delete item;                   // not exactly here, but some where in your code
    

    BTW, you don't have to do new. You can possible create a MyItem object on the stack as

    MyItem anotherItem;
    
    0 讨论(0)
  • 2020-12-05 18:36

    You've mixed

    MyItem item;
    

    which allocates an instance of MyItem on the stack. The memory for the instance is automatically freed at the end of the enclosing scope

    and

    MyItem * item = new MyItem;
    

    which allocates an instance of MyItem on the heap. You would refer to this instance using a pointer and would be required to explicitly free the memory when finished using delete item.

    0 讨论(0)
提交回复
热议问题