tags:

views:

124

answers:

4

Having construction in a form:

struct Node
{
Node():left_(nullptr), right_(nullptr)
{ }
int id_;
Node* left_;
Node* right_;
};

I would like to enable syntax:

Node parent;
Node child;
parent.right_ = child;

So in order to do so I need:

Node& operator=(Node* left, Node right);

but I'm getting msg that operator= has to be a member fnc; Is there any way to circumvent this restriction?

+4  A: 

Operator =() must be a member. And you can't overload the meaning of assignment for pointers.

anon
+5  A: 

Why not just use parent.right_ = &child? Creating an overloaded operator that assigns a value-type to a pointer would, if possible, be a very bad idea. It would obfuscate what really happens and make the code much harder to understand for someone who reads it.

Well, you already accepted an answer, but anyway, you could do what the guys that wrote Boost.Format did and just choose some other operator that can be overloaded as non-member function and has a low potential of conflicts (they chose %). In my opinion this is slightly less obfuscating.

Space_C0wb0y
Because having operato= on pointers I could in one step to this same assignment for child object (inside this operator body).
There is nothing we can do
So you want to implement a double linked list/tree or you want to chain assignments?
Space_C0wb0y
I'm doing an excersise from TC++PL and I just wanted to do it the way I've mentioned.
There is nothing we can do
Added a suggestion that might interest you.
Space_C0wb0y
"In my opinion this is slightly less obfuscating" - I think you may be alone in this.
anon
+2  A: 

An automatic conversion from value to pointer creates lots of possibilites to make your code hard to understand.

If you still want to do it you can provide a conversion operator on your Node class:

operator Node* () { return this; }
Anders Abel
@Neil Butteerworth but I think he is giving this example as caveat emptor. He doesn't claim that this is the better way
There is nothing we can do
+2  A: 

Replace

parent.right_ = child;

with

parent.right_ = &child;

and it wil work;

Nikolai N Fetissov