本文介绍了关于重载运算符的ADL或命名冲突有不同的规则吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我认为这个例子最好地说明了我的问题:I think this example best illustrates my question:namespace N { class C { public: friend bool operator==(const C& c, const C& x) { return true; } friend bool f(const C& c, const C& x) { return true; } }; class D { public: bool operator==(const D& x) { bool a = C{} == C{}; // this works return true; } bool f(const D& x) { bool a = f(C{}, C{}); // this does not work return true; } };} 我一直认为重载运算符就像函数语法'如果你愿意。我只是注意到上述区别,但在ADL或名称查找规则(我不知道哪一个)。 I have always viewed overloaded operators as being just like function except for the 'calling syntax' if you will. I just noticed the above difference however in ADL or name lookup rules (I don't know which one). 有人可以解释为什么找到 bool operator ==(const C& c,const C& x)但 bool f(const C& c,const C& x)不是?Can someone explain why the bool operator==(const C& c, const C& x) is found but the bool f(const C& c, const C& x) is not?推荐答案您的 D :: f 是隐藏 C :: f ;如果你将后者重命名为 C :: g 并调整调用,那么它工作正常(显示该函数可以找到和 Your D::f is hiding C::f; if you rename the latter to C::g and adjust the call then it works fine (showing that the function can be found and accessed just fine).您的代码实际上并不直接调用操作符函数,但这是由语言完成的。因此,您不使用运算符函数的名称,因此不适用名称隐藏。Your code isn't actually directly calling the operator functions, but this is done for you by the language. Consequently you're not using the name of the operator function, so no name hiding applies.如果写 operator ==(C {},C {})(而不是 C {} == C {} 与 f(C {},C {})相同的行为( demo )。If you write operator==(C{}, C{}) (instead of C{} == C{}), then you'll see the same behaviour as f(C{}, C{}) (demo).因此,当你说我一直把重载的操作符看作是函数, So, when you say "I have always viewed overloaded operators as being just like function except for the 'calling syntax' if you will", you've already hit the nail on the head.这里有一些标准的:complex z = a.operator+(b); // complex z = a+b;void* p = operator new(sizeof(int)*n); - 结束示例] —end example ] [C ++ 11:3.3.7 / 4]: [..] 4)函数隐藏其范围扩展到或超过成员函数类的结束的同名的声明。 [..] [C++11: 3.3.7/4]: [..] 4) A name declared within a member function hides a declaration of the same name whose scope extends to or past the end of the member function’s class. [..] [C ++ 11:3/4]:名称是使用标识符(2.11), operator-function-id (13.5), literal-operator-id conversion-function-id (12.3.2)或 template-id (14.2) .4,6.1)。[C++11: 3/4]: A name is a use of an identifier (2.11), operator-function-id (13.5), literal-operator-id (13.5.8), conversion-function-id (12.3.2), or template-id (14.2) that denotes an entity or label (6.6.4, 6.1).([qualified] operator-function-id c $ c> :: N :: C :: operator == 。)(The [qualified] operator-function-id here is ::N::C::operator==.) 这篇关于关于重载运算符的ADL或命名冲突有不同的规则吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-28 08:14