Right way to initialize a pointer in a constructor

后端 未结 3 979
一向
一向 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 10:58

    I'm not really sure why you want to store a pointer to an int inside a class, rather than just storing the value directly (and not have a pointer be the input to the constructor), but assuming you do actually want that, here's how you'd do it:

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

    But this is really, really terrible style, and you have to have a good reason for doing it. You also need to remember to free the pointer at class destruction:

    ~MyInt(){delete MyValue;}
    

提交回复
热议问题