[英]How to access dynamic array inside a class constructor?
如何訪問動態數組並為其設置值? 例如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();
//.....;
}
您創建的數組是private
,要訪問它,您必須提供一個accessor方法:
public:
...
int* getPtr() { return ptr; }
...
int *ptr = arry.getPtr();
ptr[0] = 1;
cout << ptr[0];
或者,您可以隱藏指針本身,並提供get(position)
和set(position)
方法,以確保其他代碼不會與您的指針混淆。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.