Operator Overloading [] & =

I know how to overload operators now, but now I want to know if there's an operator function to combine the [] and = operators to change the value of an encapsulated piece of data, like a node in a queue/stack.

Any suggestions would be great and examples even more welcome.
There are two operators: one is = and other is []. You can combine them in expression to get the needed result.
Last edited on
Could you show me an example? I can't get the implementation right for the life of me.
You wrote in the first post that "I know how to overload operators now". So you should overload two operators: = and [].

SomeClass obj;

obj[0] = SomeValue;
Last edited on
Using this node struct as an example:
1
2
3
4
5
6
struct node
{
    node* next;
    node* prev;
    int data;
};


Would the [] operator return the data, and the = operator is programmed to modify the data in the node?

1
2
3
4
5
6
7
8
9
10
11
// In the main object
int operator[](int index)
{
    return array[index]->data; // Array holding address values of nodes
}

// In the node object
void operator=(int newdata)
{
    data = newdata;
}
I have not understood is it a wrong statement that you know how overload operators? Why are you asking me about this if you know?
The trick is to let operator[] return a reference
1
2
3
4
int& operator[](int index)
{
	return array[index]->data;
}

No need to overload operator=.
Well, I think I understand it now. Thank you for your time. Sorry if I wasn't clear about some parts.
The compiler doesn't resolve everything at the same Time. It does it in steps. In this case it resolves the the [] operator first to returns reference and then assigns the value. Because c++ operates automatically on predefined types, you don't need to overload the = operator. You would though if it returned a user defined type.
You would only need to do that if the implicitly defined operator= isn't what you want.
Last edited on
Topic archived. No new replies allowed.