为什么在 c++ 中重载运算符时不需要范围解析 (::)?

Why isn't the scope resolution (::) needed when overloading operators in c++?

本文关键字:范围 不需要 c++ 重载 运算符 为什么      更新时间:2023-10-16

通常,当您在类声明中声明一个方法并在外部定义它时,您需要指定其作用域。

由于我读到运算符几乎是常规方法,因此我发现很难理解以下行为:

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+是一个自由函数,与A类完全无关。碰巧它的一个参数是类A.

这意味着它与A::operator+定义为:

class A {
public:
    const A operator+(const int);
};

在代码示例中,您将为类定义一个friend函数。因此,free 函数现在可以访问类的私有和受保护部分。如果你不定义它(operator+),friend只能访问A的公共成员。这就是为什么你要让它friend.

这是因为在这种情况下,运算符+不是类A的成员,而是一个友好的函数。

在您的情况下,运算符 + 不是类 A 的成员。这通常是定义二元运算符的正确方法,以便运算符可以与左侧的文本一起使用。

但是,大多数运算符被定义为类范围内的普通类成员。EG,

A& A::operator=(A rhs)
{
    swap(rhs);
    return *this;
}

这是一个更完整的答案:运算符重载