【发布时间】:2014-10-22 21:23:06
【问题描述】:
namespace A{
struct A{
inline void operator+(const int B) {}; // 1)
};
inline void operator+(const A& a,const int B) {}; // 2)
}
inline void operator+(const A::A& a,const int B) {}; // 3)
int main()
{
A::A a;
a+1; // compile questions
return 1;
}
上面的代码可以编译没有任何问题。
但是如果 1) 被注释掉,它会因为 2) 和 3) 中的“'a + 1' 中的 'operator+' 的重载不明确”而编译失败。我可以理解operator+是在class中先搜索的,如果1)没有注释是有原因的,编译没问题。我说的不对吗?
主要问题:如果 1) 被注释,为什么编译器找到了一个匹配的 operator+,它继续找到其他的?我也很好奇应该先找到哪个。 (根据How does the operator overload resolution work within namespaces?的信息,我认为应该立即停止)
第二个问题:
namespace A{
struct A{
inline void operator+(const long int B) {}; // 4), the input parameter type has been changed to long int
};
inline void operator+(const A& a,const int B) {}; // 5)
void test();
}
inline void operator+(const A::A& a,const int B) {}; // 6)
void A::test()
{
A a; // a)
a+ 1;
}
int main()
{
A::A a;
a+1; // b)
return 1;
}
由于 4) 和 5) 在 a) 处的编译不明确错误。
由于 4) ,5) 和 6) 在 b) 处的编译不明确错误。
问题 i)
对于a)和b),为什么编译器已经找到了operator+ with (const long int input parameter type) at 4),这是struct A中的成员操作符函数,它仍然会继续找出其他的。在我看来,编译器应该停在那里给出类型错误信息。应该和成员函数的入参类型完全匹配的情况一样,停止寻找其他的。
问题 2)
我认为编译器应该在 4) 处停止并给出类型错误信息。 在继续的情况下,为什么成员函数重载函数(long int)与具有精确匹配输入参数的非成员具有相同的分辨率排名?在这种情况下,我认为如果编译器决定继续搜索,输入参数完全匹配的非成员情况应该会获胜,这更有意义。
【问题讨论】:
标签: c++ templates namespaces overloading