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

标签 c++ operator-overloading

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

自从我读到运算符几乎都是常规方法后,我发现很难理解以下行为:

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+”?是从操作数推断出来的吗?

最佳答案

因为operator+是一个自由函数,与A类完全无关。碰巧它的一个参数属于 A 类。

这意味着它与 A::operator+ 不同,后者将被定义为:

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

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

关于c++ - 为什么在 C++ 中重载运算符时不需要范围解析 (::)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22847787/

相关文章:

c++ - 在 Qt 中使用 $HOME

c++ - 了解线程中的变量可访问性

c++ - 重载方括号运算符以接受值

c++ - 函数重载时的 Typedef 编译错误

c++ - 线程在等待锁定的互斥体时会休眠吗?

c++ - 返回对对象的 const 引用

c++对模板类的用户定义运算符的隐式转换

c++ - 第二个 const 在运算符函数中做了什么?

c++ - 在 C++ 中重载自定义字符串运算符 +=

c++ - 如何用链表重载运算符<<?