我用 C++ 和 C# 编写了以下代码
int i=0;
++i = 11;
在这个 C# 编译器带来错误之后
The left-hand side of an assignment must be a variable, property or indexer
但是 C++ 编译器生成这段代码没有错误,我得到了一个结果 11 对于 i 的值.这种差异的原因是什么?
Best Answer-推荐答案
不同的是预增运算符是左值在 C++ 中,而不是在 C# 中。 在 C++ 中 ++i 返回对递增变量的引用。在 C# 中 ++i 返回变量 i 的递增值。 所以在这种情况下 ++i 是 左值在 C++ 和 中右值 在 C# 中。
来自关于前缀增量运算符的 C++ 规范
The type of the operand shall be an arithmetic type or a pointer to a
completely-defined object type. The value is the new value of the
operand; it is an lvalue.
附言后缀增量运算符 i++ 在 C# 和 C++ 中都不是左值,因此这行代码在两种语言中都会带来错误。
int i=0;
i++ = 11;
关于c# -++i 运算符在 C# 和 C++ 中的区别,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/9516926/
|