重载运算符中没有隐式转换 [英] No implicit conversion in overloaded operator
问题描述
d1 + 4
有效,但 4 + d1
不会隐含地转换为GMan 。为什么它们不等同?
struct GMan
{
int a,b;
GMan():a(),b(){}
GMan(int _a):a(_a) int _b):a(_a),b(_b){}
GMan运算符+(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;
}
c> x + y 由C ++编译器转换为以下两个调用(取决于 x
是类类型,这样的函数存在):
>x.operator +(y);
自由功能
operator +(x,y);
现在C ++有一个简单的规则:转换可在成员访问运算符(。
)之前发生。这样,上述代码中的 x
不能在第一个代码中进行隐式转换,但可以在第二个代码中。
这个规则有意义:如果 x
可以在上面的第一个代码中被隐式转换,C ++编译器不会再知道要调用哪个函数它属于),所以它必须搜索所有现有的类匹配的成员函数。这将对C ++的类型系统造成严重破坏,并使重载规则更加复杂和混乱。
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;
}
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):
Member function
x.operator +(y);
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.
这篇关于重载运算符中没有隐式转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!