开发者

Can operator= may be not a member?

Having construction in a form:

struct Node
{
No开发者_Go百科de():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?


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.


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


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; }


Replace

parent.right_ = child;

with

parent.right_ = &child;

and it wil work;

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜