Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/156.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++;运算符重载前缀/后缀 我正在学习C++中的运算符重载。原始后缀++的属性是其优先级低于赋值运算符。例如,inti=0,j=0;i=j++;cout_C++_Operator Overloading_Postfix Operator_Prefix Operator - Fatal编程技术网

C++;运算符重载前缀/后缀 我正在学习C++中的运算符重载。原始后缀++的属性是其优先级低于赋值运算符。例如,inti=0,j=0;i=j++;cout

C++;运算符重载前缀/后缀 我正在学习C++中的运算符重载。原始后缀++的属性是其优先级低于赋值运算符。例如,inti=0,j=0;i=j++;cout,c++,operator-overloading,postfix-operator,prefix-operator,C++,Operator Overloading,Postfix Operator,Prefix Operator,您需要在增量之前而不是之后复制vec[0]和vec[1]。这样return v将返回原始值,而不是递增值 V operator++(int dummy) { V v(vec[0],vec[1]); for(int i=0; i<2; i++) { ++vec[i]; } return v; } V运算符++(int-dummy) { V(vec[0],vec[1]); 对于(int i=0;i它打印(0,0)(2,2),因为您的操作

您需要在增量之前而不是之后复制
vec[0]
vec[1]
。这样
return v
将返回原始值,而不是递增值

V operator++(int dummy)
{
    V v(vec[0],vec[1]);
    for(int i=0; i<2; i++)
    {
        ++vec[i];
    }
    return v;
}
V运算符++(int-dummy)
{
V(vec[0],vec[1]);
对于(int i=0;i它打印
(0,0)(2,2)
,因为您的操作符
++
,与内置操作符不同,它在对
V
对象进行递增之后而不是之前返回它所作用对象的副本

当操作员过载时,这完全在您的控制之下,因此您有责任使其在这方面表现得像相应的内置操作员

这就是您如何重写操作员以实现该目标的方法:

V operator++(int dummy)
{
    V v(vec[0],vec[1]); // Make a copy before incrementing: we'll return this!
    for(int i=0; i<2; i++)
    {
        ++vec[i];
    }
    return v; // Now this is *not* a copy of the incremented V object,
              // but rather a copy of the V object before incrementing!
}
V运算符++(int-dummy)
{
V(vec[0],vec[1]);//在递增之前复制一份:我们将返回这个!

对于(int i=0;i)“原始后缀++的属性是其优先级低于赋值运算符。”除非你是那种认为低优先级绑定比高优先级绑定更强的人,否则这是错误的。后增量的优先级高于赋值的优先级,但后增量返回非递增值。感谢你澄清了我的误解,我使用int I=0,j=0;I=(j++);cout测试了这个问题
V operator++(int dummy)
{
    V v(vec[0],vec[1]); // Make a copy before incrementing: we'll return this!
    for(int i=0; i<2; i++)
    {
        ++vec[i];
    }
    return v; // Now this is *not* a copy of the incremented V object,
              // but rather a copy of the V object before incrementing!
}