dimanche 5 décembre 2021

C++ Initializing Member Variables that are Containers of Object Pointers

I apologize to ask this as I'm sure it's been answered elsewhere. I am trying to initialize a container of object pointers within the constructor of my class. The container is an array template, the class for the constructor is A and the object type is class P.

A.cpp:
    #include 'Array.h'
    #include 'P.h'

    
    A::A(){
    Array<P*> ps = ?

P.cpp:
   P::P(string n){
      this->name = n;
   }


Array.h:

using namespace std;

template <typename T>
class Array {

    public:
        Array();
                
        ~Array();
        void add(int);
        int get(int index);
        int getSize();
        bool isFull();
        int& operator[] (int);
    
    private:
        int size;
        int* elements;
        static int MAX_ARR = 256;
    
};
template <typename T>
Array<T>::Array(){
    elements = new int[MAX_ARR];
    size = 0;
}
template <typename T>
Array<T>::~Array(){
    delete [] elements;
}
template <typename T>
void Array<T>::add(int t){
    if (size >= MAX_ARR)   return;
    elements[size++] = t;
}
template <typename T>
int Array<T>::getSize(){
    return size;
}
template <typename T>
bool Array<T>::isFull(){
    return size >= MAX_ARR;
}
template <typename T>
int& Array<T>::operator[](int index){
    if (index < 0 || index >= size) {
        cerr<<"Array index out of bounds"<<endl;
        exit(0);Array
    }
    return elements[index];
}

wondering what should go in the question mark/ how to properly initialize said member variable. Class P is simple, has a single string as a parameter for it's constructor.

Aucun commentaire:

Enregistrer un commentaire