[英]Please explain the following function
I have come across a function definition starting as: 我遇到了一个以以下内容开头的函数定义:
int operator*(vector &y)
{
// body
}
After putting *
just after operator and before opening brace of argument, what does this function mean? 将*
放在运算符之后,然后在打开参数大括号之前,此函数是什么意思?
This is an operator *
overload. 这是一个operator *
重载。 The syntax you should use is *(y)
while y
is of type vector
. 您应该使用的语法为*(y)
而y
的类型为vector
。
It allows you a reference like implementation, something similar to pointer reference in C. Of course the actual meaning depends on the body. 它允许您提供类似实现的引用,类似于C中的指针引用。当然,实际含义取决于主体。 eg you can return a reference to an internal element in the vector. 例如,您可以返回对向量中内部元素的引用。
这是*
运算符的函数重载。
它的函数重载使解引用运算符*
重载。
It is either a dereferencing operator or a multiplication operator override. 它可以是解引用运算符或乘法运算符覆盖。 It is dereferencing if it is in a namespace and multiplication if it is inside a class. 如果在名称空间中,则取消引用;如果在类内部,则进行乘法引用。 Since it has a body and no class scope I will also assume that it is a dereferencing. 由于它具有主体并且没有类作用域,因此我还将假定它是一个取消引用。
Actually its not a deferencing operator as in *ptr! 实际上,它不是* ptr中的延迟运算符! Its actually an operator such as a multiplication operator. 它实际上是一个运算符,例如乘法运算符。 Here is a simple example 这是一个简单的例子
#include <iostream>
using namespace std;
struct Int{
int val;
Int(const int val = 0) : val(val){}
int operator*(const Int& number)const{
return val * number.val;
}
};
int main(){
Int n(4), m(5);
cout << n * m << endl; //use the operator*() implicitly
cout << (n.operator*(m)) << endl; //use the operator* explicitly
}
To define a de-ferenceing operator, its prototype would be operator*(). 要定义去引用运算符,其原型应为operator *()。 Look here for more information. 在这里查看更多信息。 Here is a live code to test. 这是要测试的实时代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.