Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
344 views
in Technique[技术] by (71.8m points)

c++ - No implicit conversion in overloaded operator

d1 + 4 works but 4 + d1 doesn't even though 4 can be converted implicitly to a GMan. Why aren't they equivalent?

struct GMan
{
    int a, b;

    GMan() : a(), b() {}
    GMan(int _a) : a(_a), b() {}
    GMan(int _a, int _b) : a(_a), b(_b) {}

    GMan operator +(const GMan& _b)
    {
         GMan d;
         d.a = this->a + _b.a;
         d.b = this->b + _b.b;
         return d;
    }
};

int main()
{
    GMan d1(1, 2), d(2);
    GMan d3;
    d3 = d1 + 4; 
    d3 = 4 + d1;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A call x + y is translated by the C++ compiler into either of the following two calls (depending on whether x is of class type, and whether such a function exists):

  1. Member function

    x.operator +(y);
    
  2. Free function

    operator +(x, y);
    

Now C++ has a simple rule: no implicit conversion can happen before a member access operator (.). That way, x in the above code cannot undergo an implicit conversion in the first code, but it can in the second.

This rule makes sense: if x could be converted implicitly in the first code above, the C++ compiler wouldn’t know any more which function to call (i.e. which class it belongs to) so it would have to search all existing classes for a matching member function. That would play havoc with C++’ type system and make the overloading rules even more complex and confusing.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...