Right way to initialize a pointer in a constructor

后端 未结 3 978
一向
一向 2021-01-28 10:40

I have the following exercise:

Add code to make it run properly.

class MyInt
{
public:

private:
    int* MyValue;
}

int main(int argc,char** a         


        
3条回答
  •  既然无缘
    2021-01-28 11:19

    Another way:

    MyInt(int x) : MyValue(new int(x)) {}
    

    This doesn't require the additional member. However, you have to make sure that you deallocate the memory in the destructor.

    ~MyInt() { delete MyValue; }
    

提交回复
热议问题