简体   繁体   中英

Pointer in constructor and member function return different addresses

HelloI got a problem when i compiled my program. Why the pointer intArray gives different addresses in constructor and member function display() in same object?Thank you!

#include<iostream>
using namespace std;
class MyClass
{   private:
      int* intArray;
      int arraySize;
    public:
      MyClass(int*,int);
      ~MyClass()
      {delete []intArray;};
      void display();
};
MyClass::MyClass(int intData[],int arrSize)
{     int *intArray = new int[arrSize];
      cout<<intArray<<"   "<<endl;
};
void MyClass::display()
{     cout<<intArray<<"   "<<endl;
}
int main()
{     int Data[10]={9,8,7,6,5,4,3,2,1,0};
      MyClass obj1(Data,10);
      obj1.display();
}

In the constructor, you declare a local variable which hides the member. Both members are left uninitialised, so calling display will show the uninitialised value.

You probably want something along the lines of

MyClass::MyClass(int intData[],int arrSize) :
    intArray(new int[arrSize]),
    arraySize(arrSize)
{
    // assuming the input array specifies initial values
    std::copy(intData, intData+arrSize, intArray);
}

Since you're dealing with raw pointers to allocated memory, remember to follow the Rule of Three to give the class valid copy semantics. Then, once you're happy with your pointer-juggling skills, throw it away and use std::vector instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM