私はこれをテストしましたが、うまくいきました:
#include <vector>
// Forward declaration of the class
class CatArray;
class Cat {
// This line means that the CatArray class can
// access the private members of this class.
friend class CatArray;
private:
static int ID;
public:
void dog(const char* value) {
// Use ID here any way you want.
}
};
// Static variables need to be defined.
int Cat::ID = 0;
class CatArray {
private:
std::vector<Cat> cats;
public:
// explicit means that the argument passed to this constructor must
// be an unsigned int. The ": cats(size)" part is an initializer
// list that initializes the cats vector so that it would have the
// specified size.
explicit CatArray(unsigned int size) : cats(size) {}
Cat& operator [](unsigned int index) {
Cat::ID = index;
return cats[index];
}
};
次のように使用します。
CatArray cats(18);
cats[1].dog("oh lol hi");
このメソッドは、宣言する任意の数の配列に対して機能します。