[英]Overloading assignment operator: if we return (*this), which is a value at a pointer/address, what's right syntax for assignment operator?
[英]Why assignment operator = doesn't return the value of pointer but the dereference value?
从任务返回什么? :
赋值表达式在赋值后具有左操作数的值
这个代码:
#include <iostream>
using namespace std;
int main() {
int a[5] = { 0,1,2 };
int* a_ptr = a;
int b = (*a_ptr++ = 3); //int *b won't compile
cout << b << endl; //3
}
求值(*a_ptr++ = 3)
时=
的左操作数是什么?
操作数的定义是什么? 在我看来,操作数是aptr
的标识符或名称。
int b = (*a_ptr++ = 3);
被分组为int b = (*(a_ptr++) = 3);
. 注意括号是多余的; 你可以写
int b = *a_ptr++ = 3;
这在许多方面使结果更加明显,因为=
的从右到左的结合性使得 3 延续到b
的值。
a_ptr++
是一个等于a_ptr
的表达式,但一旦整个语句完成,它将指向数组a
的第二个元素。 由于您不使用该递增指针,因此++
是一个红鲱鱼,因此该语句简化为
int b = *a_ptr = 3;
因此很明显*a_ptr = 3
具有将数组a
的第一个元素设置为 3 的效果,并且是一个等于 3 的表达式,它被分配给b
。
左操作数是*a_ptr++
。 根据 运算符优先级,它被评估为
*(a_ptr++)
在执行语句之后,后增量作为副作用进行排序。 操作数的值是语句的结果。 所以,它相当于
int b = (*a_ptr = 3);
a_ptr++;
也就是说,一般来说,操作数是运算符对其进行操作或工作的表达式或值。 所以,可以
var
,如int var
)5
或 '"Hello"')*a_ptr++
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.