- #1
yungman
- 5,718
- 241
I have been studying overloading [ ]. I understand how it works from the book. I experiment using vector of structure and obviously I can't make it work. I wonder if it is possible to overload [] on vector of structure. Here is what I have and it's not even close to working, what can I do to make this work?
In the code, I try to return Ivar[position].amount, it flagged me. In fact, it flagged me to put vector<Directory>Ivar(3) inside the class definition.
Is it possible to make this work?
Thanks
C++:
#include <iostream>
#include <vector>
using namespace std;
class VecA
{
private:
struct Directory { char name[25]; int amount; };
vector<Directory>Ivar(3);
public:
VecA(int sub1, int sub2, int sub3) //constructor with 3 parameters of int
{Ivar[0].amount = sub1; Ivar[1].amount = sub2; Ivar[2].amount = sub3;}
int &operator[](int position){ return Ivar[position].amount;}
};
int main()
{ VecA anil(1, 2, 3);
cout << anil[0] << ", " <<anil[1] << ", " << anil[2] << "\n\n";
return 0;
}
In the code, I try to return Ivar[position].amount, it flagged me. In fact, it flagged me to put vector<Directory>Ivar(3) inside the class definition.
Is it possible to make this work?
Thanks
Last edited: