[英]Accessing array class member within class function
我有2個類Y,X。我想創建一個類X的成員,該成員是類Y的實例的數組。
class Y
{
public:
Y();
~Y();
void func();
int n;
};
我讀過某個地方,我應該使用一個指針(也許是指向數組指針的指針?)以便能夠與該數據進行交互。
class X
{
public:
X();
~X();
void setY(int n);
Y *yy;
};
因此,我嘗試在類X中創建一個函數setY來處理添加數組yy的后續元素。 我在努力
1)正確地創建類Y的實例數組2)在函數setY中-訪問數組yy的元素並與它們交互-調用函數func()(我在這里考慮的是this->指針)。
我仍然是初學者,因此我的問題似乎很明顯。
1)正確創建類Y的實例數組
創建類Y的實例數組的一種方法是:
const int N = 10;
X::X()
{
yy = new Y[N]; // create array of 10 instances of class Y.
}
2)在函數setY中-訪問數組yy的元素並與它們交互-調用函數func()(我在這里想到的是this->指針)。
void X::setY(int n)
{
assert(n < N); // check that n is less than N (10)
yy[n].func(); // access n-th element.
}
但是,還有更好的方法,例如,使用std :: vector :
#include <vector>
class X
{
public:
X();
~X();
void setY(int n);
std::vector<Y> yy;
};
X::X() : yy(N) // create std::vector of 10 instances of class Y.
{
}
void X::setY(int n)
{
yy[n].func(); // access n-th element.
}
如果您的class X
僅包含固定數量的Y實例,則可以這樣簡化:
class X
{
public:
X();
~X();
void setY(int n);
Y[10] yy;
};
X::X()
{
}
void X::setY(int n)
{
yy[n].func(); // access n-th element.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.