使用非成员函数重载运算符

发布于 2024-11-02 23:54:05 字数 83 浏览 0 评论 0原文

这个问题的答案似乎让我无法回答,但是如何使用非成员函数进行重载。您是否只是创建一个程序级函数,并且无论原型(或定义)存在哪里,运算符都会为该类类型重载?

The answer to this question seems to escape me, but how do you go about overloading with non-member functions. Do you just create a program level function and where ever the prototype (or definition) exists the operator is overloaded for that class type?

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

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

发布评论

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

评论(1

我很OK 2024-11-09 23:54:05

对于成员函数,this 将是左侧参数,这意味着您的运算符只有一个参数(对于一元运算符则没有)。对于独立函数,您必须分别为二元或一元运算符提供两个或一个参数。

一个很好的例子是流的 << 运算符:

class T;

// ...

std::ostream & operator<<(std::ostream &os, const T &val)
{
    // ...
    return os;
}

这里,os 是左侧参数,val 是右手边一个。

至于“where”,必须在使用它的地方定义该运算符。一般来说,将它们放在与您要重载运算符的类型相同的位置。

编辑:

对于重要的运算符(基本类型的算术运算),运算符是函数调用的语法糖。当你这样做时:

std::cout << "Hello";

就像写:

operator<<(std::cout, "Hello");

但更具可读性。

对于成员运算符,左侧参数将为 this (这就是成员运算符少一个参数的原因)。

With a member function, this would be the left hand side parameter, meaning your operator would only have one argument (or none for unary operators). With a freestanding function, you must supply either two or one arguments for binary or unary operators, respectively.

A good example is the << operator for streams:

class T;

// ...

std::ostream & operator<<(std::ostream &os, const T &val)
{
    // ...
    return os;
}

Here, os is the left hand side parameter, and val is the right hand side one.

As for "where", the operator must be defined where you use it. Generally, put them at the same place as the type you're overloading the operators for.

EDIT:

For non trivial operators (arithmetic operations on primitive types), operators are syntactic sugar for function calls. When you do this:

std::cout << "Hello";

It's like writing that:

operator<<(std::cout, "Hello");

But more readable.

For member operators, the left parameter will be this (and that's why member operators have one less argument).

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