Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can operator= may be not a member?

Tags:

c++

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?

like image 832
There is nothing we can do Avatar asked Oct 29 '25 01:10

There is nothing we can do


1 Answers

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.

like image 177
Björn Pollex Avatar answered Oct 31 '25 14:10

Björn Pollex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!