Frage

Good day guys.

I have the following struct and class,

template <class T>
struct Node
{
    T DataMember;
    Node* Next;
};

template <class T>
class NCA
{
    public:
        NCA();
        ~NCA();
        void push(T);
        T pop();
        void print();
        void Clear();
    private:
        Node<T>* Head;
        void* operator new(unsigned int);
};

I would like to instantiate the class with a size

ie. NCA[30] as one would any array

War es hilfreich?

Lösung

If the compiler were to allow you to use brackets in your object constructor, how would it know whether you were trying to make an NCA of size 30 or an array of 30 NCA objects? C++ does not allow you to override the bracket syntax, except as an operator once you already have an object.

Andere Tipps

You can't. But, you can do something almost like that: initialize it with parenthesis, but not brackets:

NCA<int> myList(30);

Implement it like so:

template <class T>
class NCA
{
  ...
  public:
    explicit NCA(std::size_t count);
  ...
 };

template <class T>
NCA<T>::NCA(std::size_t count) {
  ... allocate Head, &c ...
  while(count--)
    push(T());
}

That's not quite how operator[] works.

When you write NCA[30] you're writing type[30], where as to use operator[] you need an instance:

NCA inst;
inst[30];

What you can do though is use an integer template parameter to specify the size, e.g.:

#include <utility>

template <std::size_t N>
class NCA {
  char bytes[N];
};

int main() {
  NCA<1024> instance;
}

You can't.

You can only use the ctor to do it like:

NCA n(30);
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top