在类内部或外部重载运算符有什么区别?

发布于 2024-10-30 13:54:24 字数 473 浏览 1 评论 0原文

在C++中,我知道有两种重载方法。我们可以在内部(如类a)或外部(如类b)重载它。但是,问题是,这两者在编译时或运行时有什么区别吗?

class a
{
public:
    int x;
    a operator+(a p) // operator is overloaded inside class
    {
        a temp;
        temp.x = x;
        temp.x = p.x;
        return temp;
    }
};

class b
{
public:
    friend b operator+(b, b);
    int x;
};

b operator+(b p1, b p2) // operator is overloaded outside class
{
    p1.x += p2.x;
    return p1;
}

In C++, i know there are two ways to overload. We can overload it inside (like class a) or outside (like class b). But, the question is, is there any difference between these two either in compile time or runtime or not?

class a
{
public:
    int x;
    a operator+(a p) // operator is overloaded inside class
    {
        a temp;
        temp.x = x;
        temp.x = p.x;
        return temp;
    }
};

class b
{
public:
    friend b operator+(b, b);
    int x;
};

b operator+(b p1, b p2) // operator is overloaded outside class
{
    p1.x += p2.x;
    return p1;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不疑不惑不回忆 2024-11-06 13:54:24

成员operator+要求LHS为a - 自由运算符要求LHSRHS为b另一边可转换为 b

struct Foo {
    Foo() {}
    Foo(int) {}
    Foo operator+(Foo const & R) { return Foo(); }
};


struct Bar {
    Bar() {}
    Bar(int) {}
};

Bar operator+(Bar const & L, Bar const & R) {
    return Bar();
}


int main() {
    Foo f;
    f+1;  // Will work - the int converts to Foo
    1+f;  // Won't work - no matching operator
    Bar b;
    b+1;  // Will work - the int converts to Bar
    1+b;  // Will work, the int converts to a Bar for use in operator+

}

The member operator+ requires the LHS to be an a - The free operator requires LHS or RHS to be a b and the other side to be convertible to b

struct Foo {
    Foo() {}
    Foo(int) {}
    Foo operator+(Foo const & R) { return Foo(); }
};


struct Bar {
    Bar() {}
    Bar(int) {}
};

Bar operator+(Bar const & L, Bar const & R) {
    return Bar();
}


int main() {
    Foo f;
    f+1;  // Will work - the int converts to Foo
    1+f;  // Won't work - no matching operator
    Bar b;
    b+1;  // Will work - the int converts to Bar
    1+b;  // Will work, the int converts to a Bar for use in operator+

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文