通常情况下,当你在类声明中声明一个方法,并在外部定义它时,你需要指定它的作用域。
由于我已经读到运算符基本上是普通方法,我很难理解以下行为:
class A
{
public:
A(int x)
{ this->x = x;}
int foo();
friend const A operator+ (const A& left,const int right);
private:
int x;
};
const A operator+ (const A& left,const int right) //can't be A::operator+
{
return A(left.x + right);
}
int A::foo() // A:: is needed here
{
return 5;
}
int main(int argc, char **argv) {
A a(1);
a = a + 4;
a.operator =(a+5);
a.foo();
}
为什么我们不需要指定要定义/重载哪个 "operator+"?操作数是否可以推断出来?
class A
相关联。然而,这个运算符也可以通过未限定的查找找到。我在评论中提到的不是 ADL,而是一般情况下的运算符名称查找。 - dyp