重载的++运算符不是用c ++编写的

时间:2016-03-23 11:09:41

标签: 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;
}

3 个答案:

答案 0 :(得分:7)

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

  circle operator++ ( int );

答案 1 :(得分:5)

重载运算符的signature应为:

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 
}

这里有online demo来显示两者之间的差异。

答案 2 :(得分:0)

这是版本前缀和后期修复。您可以在调用时添加一些代码,例如 c1 ++(1); (当然,如果需要)

http://www.example.com/api/create_post/?nonce=123456789&title=My%20Post&status=publish
相关问题