How to overload [][] operator in C++.NET

  • Thread starter Thread starter vcmkrishnan.techie
  • Start date Start date
V

vcmkrishnan.techie

Hi all,

In managed C++, can I overload the operator [] to access data members
in the following way

Create object objTime;
seconds = obj["Hour"]["Min"];
or
seconds = obj[12][45];

Thanks
Mohan
 
Hi all,

In managed C++, can I overload the operator [] to access data members
in the following way

Create object objTime;
seconds = obj["Hour"]["Min"];
or
seconds = obj[12][45];

You have to overload operator[] to return a object which itself overloads
operator[].

-cd
 
////////////////////////////////////////
/// Base Structure
////////////////////////////////////////
struct baseStruct
{
public:
virtual baseStruct& operator [](string Str)
{
return *this;
}
};

////////////////////////////////////////
///Main class deriverd from BaseStruct
////////////////////////////////////////


__nogc class MainClass : public baseStruct
{
int IndexCount; /// loop count, 3 times rotate
/// if the operator is [][][]

string Str1; /// the three string arguments;
string Str2;
string Str3;


public:
baseStruct *DataPtr; // a pointer to Data Base struct

MainClass ()
{
IndexCount = 0;
Str1 = "";
Str2 = "";
Str3 = "";

}

virtual baseStruct& operator [](string Str)
{

if (IndexCount == 0)
{
IndexCount++;
Str1 = Str;
return *this;

} else if (IndexCount == 1)
{
IndexCount++;
Str2 = Str;
return *this;

} else if (IndexCount == 2)
{
Str3 = Str;
cout << Str1 << " " << Str2<< " " <<Str3<< endl;

IndexCount = 0;
Str1 = "";
Str2 = "";
Str3 = "";
return *DataPtr;
}

/*return *this;*/
}


};
 
Back
Top