DLCom
DLCom

Reputation: 11

C++ array like class element definition

I want to create a smaller vector class for a microcontroller.

In the normal vector class, your can do something like:

myvector[1] = 100;

How is it possible to achieve such an assignment in a class?

I tried this:

template<typename T>
class Vector
{
 private:
    T* content;
 public:
    T* operator[](unsigned int);
};
template <typename T>
T* Vector::operator[](unsigned int i)
{
    return &content[i];
}

But, that throws errors, and it would also not be a nice solution.

So what should I do?

Upvotes: 1

Views: 411

Answers (1)

Eric Sage
Eric Sage

Reputation: 86

In the case you display above, you are returning a pointer to the value, which is presumably why you are having difficulties. Consider returning a reference instead:

T& operator[](unsigned int);

Upvotes: 2

Related Questions