Domanda

Basically, I'm trying to make template map/dictionary class for c++ (I know this have already been done, assume I'm masochistic).

I started up, writing this skeleton:

#pragma once
template <class T>
class AssArray
{
    int _size;
    int _position;

public:
    AssArray(int size);
    ~AssArray(void);

    const T& operator [](char* b) const;
    T& operator [](char* b) const;
        //I read this should be done sth like this when researching, though an explanation would be nice.
};

Now, I need to be able to get (T=AssArray["llama"]), set (AssArray["llama"]= T) and override (AssArray["llama"]= newT).

Doing this is pretty straight forward, just loop it through etc, the real problem here is the operators;

if I use AssArray["llama"]= T, how am I supposed to get the value of T into the operator overloading-function?

I've only found explanations describing the solutions briefly, and can not really follow.
Please enlighten me.

È stato utile?

Soluzione

All you have to do is correct your signatures like so:

const T& operator [](char* b) const;
T& operator [](char* b);

I've removed the const qualifier from the second operator.

if I use AssArray["llama"]=T, how am I supposed to get the value of T into the operator overloading-function?

You don't. You just return a reference to where the new value should be stored, and the compiler will take care of the rest. If "llama" does not exist in the array, you need to create an entry for it, and return a reference to that entry.

Altri suggerimenti

Since the operator[] returns a reference to T if you want to say assArray["str"] = T the type T has to know what to do with the operator=. If T does not have the operator= overloaded you have to overload the operator= in type T.

operator[] has nothing to do with assignments. It should just return the element at the given index.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top