繁体   English   中英

重载的++运算符在c ++中不起作用

[英]overloaded ++ operator isn't working in c++

有人可以向我解释为什么我的重载++(预版本)没有更新值吗? 片段是这样的:

circle circle:: operator++()
{  
    Area = Area * 2.0;
    return *this; 
}
/////////////////////////////

int main()
{
    class circle c1(4, 1, -1), c2(12, 4, 6);
    c1.output();
    c1++;
    c1.output();

    system("pause");
    return 0;
}

这是因为你重载前缀并调用后缀。 你需要调用++c1; 使用c1++; 你还需要重载postfix:

  circle operator++ ( int );

您的重载运算符的签名应该是:

circle& operator++();   // return by reference and this is prefix. 

但你使用postfix,所以它应该是:

circle operator++ (int);   // int is unused

更改签名是不够的,因为您实现了前缀逻辑,直接更改值而不保存初始值。 因此,如果你在类似(c++).output()的组合表达式中使用postfix运算符,那么它就不会尊重预期的语义。

这里是两个版本的实现:

circle& operator++ () {  // prefix
    Area = Area * 2.0;   // you can change directly the value
    cout << "prefix"<<endl; 
    return *this;        // and return the object which contains new value
}

circle operator++ (int) {  // postfix
    circle c(*this);     // you must save current state 
    Area = Area * 2.0;   // then you update the object 
    cout << "postfix"<<endl; 
    return c;            // then you have to return the value before the operation 
}

这里有一个在线演示,以显示两者之间的差异。

这是版本前缀和后期修复。 并且你可以在调用类的情况下添加一些代码 (当然,如果需要)

circle circle:: operator++() // prefix version
{  
    Area = Area * 2.0;
    return *this; 
}

circle& circle::operator++( int n ) {    //postfix version
    if( n != 0 )                // Handle case where an argument is passed.
       //some code
    else
        Area = Area * 2.0;       // Handle case where no argument is passed.
    return *this;
}


int main()
{
    class circle c1(4, 1, -1), c2(12, 4, 6);
    c1.output();
    c1++;
    ++c1;
    c1.output();

    system("pause");
    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM