C# 一元加运算符有什么作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/727516/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 22:43:56  来源:igfitidea点击:

What does the unary plus operator do?

c#c++cunary-operator

提问by vrish88

What does the unary plus operator do? There are several definitions that I have found (hereand here) but I still have no idea what it would be used for. It seems like it doesn't do anything but there has be a reason for it, right?

一元加运算符有什么作用?我找到了几个定义(这里这里),但我仍然不知道它的用途。看起来它没有做任何事情,但它有它的原因,对吧?

采纳答案by Jeffrey Hantin

It's there to be overloaded if you feel the need; for all predefined types it's essentially a no-op.

如果你觉得有需要,它就会超载;对于所有预定义的类型,它本质上是一个空操作。

The practical uses of a no-op unary arithmetic operator are pretty limited, and tend to relate to the consequences of using a value in an arithmetic expression, rather than the operator itself. For example, it can be used to force widening from smaller integral types to int, or ensure that an expression's result is treated as an rvalue and therefore not compatible with a non-constreference parameter. I submit, however, that these uses are better suited to code golf than readability. :-)

无操作一元算术运算符的实际用途非常有限,并且往往与在算术表达式中使用值的后果有关,而不是运算符本身。例如,它可用于强制从较小的整数类型扩展到int,或确保将表达式的结果视为右值,因此与非const引用参数不兼容。然而,我认为这些用途更适合编码高尔夫而不是可读性。:-)

回答by Michael Meadows

EDITRewrote completely, because I was waaaayyy off in my original answer.

编辑完全重写,因为我在最初的答案中被忽略了。

This should allow you to handle the explicit declaration of your type as a positive value (I think in mostly non-mathematical operations). It seems that negation would be more useful, but I guess here's an example of where it might make a difference:

这应该允许您将类型的显式声明处理为正值(我认为主要是在非数学运算中)。似乎否定会更有用,但我想这是一个可能会产生影响的例子:

public struct Acceleration
{
    private readonly decimal rate;
    private readonly Vector vector;

    public Acceleration(decimal rate, Vector vector)
    {
        this.vector = vector;
        this.rate = rate;
    }

    public static Acceleration operator +(Acceleration other)
    {
        if (other.Vector.Z >= 0)
        {
            return other;
        }
        return new Acceleration(other.Rate, new Vector(other.vector.X, other.Vector.Y, -other.vector.Z));
    }

    public static Acceleration operator -(Acceleration other)
    {
        if (other.Vector.Z <= 0)
        {
            return other;
        }
        return new Acceleration(other.Rate, new Vector(other.vector.X, other.Vector.Y, -other.vector.Z));
    }

    public decimal Rate
    {
        get { return rate; }
    }

    public Vector Vector
    {
        get { return vector; }
    }
}

回答by Patrick

I suppose you could use it to always make a number positive. Just overload the unary + operator to be abs. Not really worth confusing your fellow developers, unless you really just want to obfuscate your code. Then it'd work nicely.

我想您可以使用它来始终使数字为正数。只需将一元 + 运算符重载为 abs。不值得混淆你的开发人员,除非你真的只是想混淆你的代码。然后它会很好地工作。

回答by bbrown

I've seen it used for clarity, to emphasize the positive value as distinct from a negative value:

为了清楚起见,我已经看到它用于强调正值与负值不同:

shift(+1);
shift(-1);

But that's a pretty weak use. The answer is definitely overloading.

但这是一个非常弱的用途。答案肯定是超载。

回答by Euro Micelli

Not much. The general argument for allowing the overload of operator+()is that there are definitely real world uses for overloading operator-(), and it would be veryweird (or asymmetrical) if you were to allow overloading operator-()but not operator+().

不多。允许过载一般的说法operator+()是,有绝对的现实世界用途超载operator-(),那将是非常奇怪的(或不对称),如果你要允许超载operator-()但不operator+()

I believe that I first read this argument from Stroustrop, but I don't have my books with me right to verify it. I might be wrong.

我相信我首先从 Stroustrop 那里读到了这个论点,但我没有随身携带的书来验证它。我可能错了。

回答by David Thornley

Unary plus was present in C, where it did absolutely nothing (much like the autokeyword). In order to not have it, Stroustrup would have had to introduce a gratuitous incompatibility with C.

一元加号出现在 C 中,它完全没有做任何事情(很像auto关键字)。为了没有它,Stroustrup 将不得不引入与 C 的无缘无故的不兼容。

Once it was in C++, it was natural to allow an overload function, just like unary minus, and Stroustrup might have introduced it for that reason if it wasn't already there.

一旦它在 C++ 中,就很自然地允许重载函数,就像一元减号一样,如果它不存在,Stroustrup 可能会因为这个原因引入它。

So, it means nothing. It can be used as as sort of decoration to make things look more symmetrical, using +1.5 as the opposite to -1.5 for example. In C++, it can be overloaded, but it's going to be confusing if operator+()does anything. Remember the standard rule: when overloading arithmetic operators, do things like the ints do.

所以,没什么意思。它可以用作一种装饰,使事物看起来更对称,例如使用 +1.5 作为 -1.5 的反义词。在 C++ 中,它可以被重载,但如果operator+()做任何事情都会令人困惑。记住标准规则:重载算术运算符时,像ints 那样做。

If you're looking for a reason why it's there, find something about the early history of C. I suspect there was no good reason, as C was not really designed. Consider the useless autokeyword (presumably in contrast to static, now being recycled in C++0x), and the entrykeyword, which never did anything (and later omitted in C90). There's a famous email in which Ritchie or Kernighan say that, when they realized the operator precedence had problems, there were already three installations with thousands of lines of code that they didn't want to break.

如果您正在寻找它存在的原因,请查找有关 C 早期历史的一些信息。我怀疑没有充分的理由,因为 C 并不是真正设计的。考虑无用的auto关键字(大概与static现在在 C++0x 中回收的相比),以及从entry不做任何事情的关键字(后来在 C90 中被省略)。有一封著名的电子邮件,其中 Ritchie 或 Kernighan 说,当他们意识到运算符优先级有问题时,已经有三个安装了数千行代码,他们不想破坏。

回答by SingleNegationElimination

I can't cite any source for this, but I have come to understand it is for explicit type promotion, which implies lossless type conversion. That puts it at the top of the conversion hierarchy,

我不能为此引用任何来源,但我已经理解它用于显式类型提升,这意味着无损类型转换。这使它位于转换层次结构的顶部,

  • Promotion:new_type operator+(old_type)
  • Conversion:new_type(old_type)
  • Cast:operator(new_type)(old_type)
  • Coercion:new_type operator=(old_type)
  • 晋升:new_type operator+(old_type)
  • 转换:new_type(old_type)
  • 投掷:operator(new_type)(old_type)
  • 强迫:new_type operator=(old_type)

Of course, that's from my interpretation of a note in one of the microsoft (really old) c/c++ manuals that I read about 15 years ago, so take it with a grain of salt.

当然,这是我对大约 15 年前阅读的一本微软(非常古老的)c/c++ 手册中的注释的解释,所以请谨慎对待。

回答by Charles Salvia

Actually, unary plus doesdo something - even in C. It performs the usual arithmetic conversionson the operand and returns a new value, which can be an integer of greater width. If the original value was an unsigned integer of lesser width than int, it will be changed to a signedvalue as well.

实际上,一元加号确实做了一些事情 - 即使在 C 中也是如此。它对操作数执行通常的算术转换并返回一个新值,该值可以是一个更大宽度的整数。如果原始值是宽度小于 的无符号整数int,则它也将更改为一个signed值。

Usually this isn't that important, but it canhave an effect, so it's nota good idea to use unary plus as a sort of "comment" denoting that an integer is positive. Consider the following C++ program:

通常这不是那么重要,但它产生影响,因此使用一元加号作为一种“注释”来表示整数是正数并不是一个好主意。考虑以下 C++ 程序:

void foo(unsigned short x)
{
 std::cout << "x is an unsigned short" << std::endl;
}

void foo(int x)
{
 std::cout << "x is an int" << std::endl;
}

int main()
{
 unsigned short x = 5;
 foo(+x);
}

This will display "x is an int".

这将显示“x 是一个整数”。

So in this example unary plus created a new value with a different type andsignedness.

所以在这个例子中,一元加上创建了一个具有不同类型符号的新值。

回答by jkerian

The main thing unary + accomplishes is type promotion to an int for smaller-than-int data types. This can be quite useful if you're trying to print char data using std::coutas numeric data.

一元 + 完成的主要事情是将小于 int 数据类型的类型提升为 int。如果您尝试使用std::cout数字数据打印字符数据,这将非常有用。

char x = 5;
std::cout << +x << "\n";

is very different from

char x=5;
std::cout << x << "\n";

It's also available for overloading, but in practice your overload shouldbe nearly a NOP.

它也可用于重载,但实际上您的重载应该几乎是 NOP。

回答by AnT

One thing the built-in unary +does is turning lvalue into an rvalue. For example, you can do this

内置一元+做的一件事是将左值转换为右值。例如,你可以这样做

int x;
&x;

but you can't do this

但你不能这样做

&+x;

:)

:)

P.S. "Overloading" is definitely not the right answer. Unary +was inherited from C and there's no user-level operator overloading in C.

PS“重载”绝对不是正确的答案。一元+是从 C 继承的,C 中没有用户级运算符重载。