为什么在MATLAB中允许使用多个连续的加号语法? [英] Why are multiple, consecutive plusses allowable syntax in MATLAB?
问题描述
有人知道为什么它可以在MATLAB中工作吗?
Does anyone know why this works in MATLAB?
>> 1 ++ 2
ans =
3
来自C,python,Java等语言的编码,我发现这完全可以反常觉.大概解析器有一些我不了解的重要内容?
Coming from coding in C, python, Java etc, I find it most counterintuitive that this should work at all. Presumably there's something important about the parser that I don't understand?
推荐答案
plus
和 uplus
.我怀疑MATLAB将第一个+
用作plus
,而所有其他的作为uplus
.由于默认情况下uplus
只是返回后面的内容",因此您添加1
和2
,并在两者之间使用很多返回后面的内容".
There's a difference between plus
and uplus
. I suspect MATLAB takes the first +
as plus
, and all the others as uplus
. Since uplus
is by default just "return what's behind", you add 1
and 2
, and use a lot of "return what's behind" in between.
a=2;
c=+a % unitary plus
c =
2
1+2 % addition
ans =
3
1+++2 % addition and two uplusses
ans =
3
存在uplus
的原因是允许操作符在类中重载.同样的语言也适用于其他语言,例如在C#中,以允许操作员在受限类中重载.
The reason uplus
exists is to allow operator overloading in classes. The same works in other languages, e.g. in C#, to allow for operator overloading in confined classes.
在该C#线程中提到的另一个原因是将无符号短裤更改为整数,而对于MATLAB则不是这种情况:
The other reason mentioned in that C# thread is that is changes unsigned shorts to integers, which is not the case for MATLAB:
d=uint8(1)
d =
uint8
1
+d
ans =
uint8
1
a=+d
a =
uint8
1
It does, however, convert a boolean to a double, thanks to Cris Lunego for pointing that out:
+true
ans =
1
+false
ans =
0
以下内容对我来说仍然是一个谜,灵感来自相同的方法适用于多个加号[1 +++..+++ 2]
,因此所有加号在中间连续产生[1 2]
,所有其他组合(据我测试)均为3
.我问了一个与此有关的单独问题:为什么加号和一元加号在数组语法中表现出奇怪的特征?
The same works with multiple plusses, [1 +++..+++ 2]
, so with all plusses consecutively in the middle generates [1 2]
, all other combinations (as far as I tested) result in 3
. I asked a separate question about this: Why do the plus and unary plus behave strange in array syntax?
这篇关于为什么在MATLAB中允许使用多个连续的加号语法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!