++ i操作符在C#和C ++中的区别 [英] ++i operator difference in C# and C++

查看:210
本文介绍了++ i操作符在C#和C ++中的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有在C ++和C#中编写的以下代码

I have the following code written in both C++ and C#

 int i=0;
 ++i = 11;

此C#编译器出现错误后

After this C# compiler brings an error

The left-hand side of an assignment must be a variable, property or indexer

但是C ++编译器生成这个代码没有错误,我得到一个结果 11 为 i

But C++ compiler generate this code with no error and I got a result 11 for value of i. What's the reason of this difference?

推荐答案

不同之处在于pre-increment运算符是 lvalue C ++,而不在C#中。

在C ++ ++ i 中返回对增量变量的引用。在C# ++ i 中返回变量i的递增值。

在这种情况下, ++ i 是C ++中的 lvalue 和C#中的 rvalue

The difference is that pre-increment operator is lvalue in C++, and isn't in C#.
In C++ ++i returns a reference to the incremented variable. In C# ++i returns the incremented value of variable i.
So in this case ++i is lvalue in C++ and rvalue in C#.

p>

From C++ specification about prefix increment operator


操作数的类型应为算术类型或指向
完全定义的对象类型的指针。该值是
操作数的新值;它是一个左值

PS postfix增量运算符i ++不是在C#和C ++中的左值,所以这行代码将带来两种语言错误。

P.S. postfix increment operator i++ isn't lvalue in both C# and C++, so this lines of code will bring error in both languages.

 int i=0;
 i++ = 11;

这篇关于++ i操作符在C#和C ++中的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆