Right way to initialize a pointer in a constructor

后端 未结 3 1017
一向
一向 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:09

    I don't see anything in your original problem statement that requires the pointer to be initialized to the address of an int. The minimal code required to fix the example would be to add a constructor that takes an int, and initialize MyValue to nullptr.

    class MyInt
    {
    public:
        MyInt(int) {}
    private:
        int* MyValue = nullptr;
    };
    
    int main(int argc,char** argv)
    {
     MyInt x(1);
     return 0;
    }
    

    If your compiler doesn't support C++11 then

    class MyInt
    {
    public:
        MyInt(int) : MyValue(NULL) {}
    private:
        int* MyValue;
    };
    

提交回复
热议问题