简体   繁体   中英

How to access dynamic array inside a class constructor?

How do I access the dynamic array and set values to it? For example array[size] = {8, 4, 3, 2, ...}

class Array
{
public:
    Array(int sze)// default constructor
    {
        size = sze;
        ptr = new int [size];
    }

private:
    int size; // number of elements in the Array
    int *ptr = 0; // address of dynamically allocated memory

};

int main()
{
    Array arry(10);
    cout << arry.getSize();

    //.....;
}

Your array that you have created is private , and to access it you must provide an accessor method:

public:
    ...
    int* getPtr() { return ptr; }
...
int *ptr = arry.getPtr();
ptr[0] = 1;
cout << ptr[0];

Alternatively you can hide the pointer itself and provide get(position) and set(position) methods to ensure that other code doesn't mess with your pointer.

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