简体   繁体   English

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

[英]Overloading operators with non-member functions

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? 您是否只是创建一个程序级别的函数,并且在原型(或定义)存在的地方,该类类型的操作符就会重载?

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). 对于成员函数, this将是左侧参数,这意味着您的运算符将仅具有一个参数(对于一元运算符则没有参数)。 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. 在这里, os是左侧参数,而val是右侧参数。

As for "where", the operator must be defined where you use it. 至于“ where”,必须在您使用的地方定义运算符。 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). 对于成员运算符,left参数将是this (这就是为什么成员运算符少一个参数的原因)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM