Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two operators simultaneity overload in c++

I want to represent my object like an array. I mean that the programmer can write in his code

myobject[3]=2

In the back (in myobject code) there isn't an array at all, it's only representation.

So I need to overload [] and = simultaneously. How can this be done?

thank you, and sorry about my poor English.

like image 815
yoni Avatar asked Oct 02 '11 19:10

yoni


1 Answers

operator[] should return a reference to object you are trying to modify. It may be some kind of metaobject, that overloads operator= to do whatever you wish with your main object.

Edit: As the OP clarified the problem, there is a way to do this. Look here:

#include <vector>
#include <iostream>

int & func(std::vector<int> & a)
{
    return a[3];
}

int main()
{
    std::vector<int> a;
    a.push_back(1);
    a.push_back(2);
    a.push_back(3);
    a.push_back(4);
    func(a) = 111;
    std::cout << a[3] << std::endl;
}
like image 164
Griwes Avatar answered Oct 06 '22 01:10

Griwes