Re: Overloading Subscript operator
There are a couple issues with your code:
1) assuming your [] operator works, the return type is a temporary const
T & that cannot be assignee.
2) it's awkward to really tell the compiler to pick up the template
argument, check the following code:
I did some rethinking. following is what I really want.
#include "stdafx.h"
#include <map>
#include <list>
using namespace std;
class A
{
private:
string a;
string b;
string c;
public:
A(){}
};
class B
{
private:
string a;
string b;
string c;
public:
B(){cout << "B constructor is being called \n";}
};
class C
{
private:
map<string, A *> aobj;
map<string, B *> bobj;
string cur_key; //store the current key here till a
//valid = operator is called.
public:
C(){cout << "Constructor of C called \n";}
//Get the current key for the map.
string operator [] (string key)
{
cur_key = key;
cout << "Operator [] called " << key.c_str() << endl;
return key;
}
//Insert object A into aobj map with the key stored in cur_key
int operator = (A* a)
{
aobj.insert(make_pair(cur_key, a));
cout << "Operator = A* called \n";
return 1; //Should be an iterator object
}
//insert object B into bobj map with the key stored in cur_key
int operator = (B *b)
{
cout << "Operator = B* called \n";
}
};
int _tmain(int argc, _TCHAR* argv[])
{
C c;
A *a = new A();
c["abcd"] = a;
return 0;
}
As you can see, c["abcd"] will call the [] operator and set the
current key. Then the overloaded assignment operator is called to
insert the object into relevant maps.
The problem is that it won't compile. It gives an error.
error C2679: binary '=' : no operator found which takes a right-hand
operand of type 'A *' (or there is no acceptable conversion)
What is that I am doing wrong here.
~raan