关于C++类中++的运算符重载问题,后置自增表达式不行?
巴扎黑
巴扎黑 2017-04-17 13:35:01
0
2
717

在程序设计基础这本书中写的是:
后置自增表达式 Aobject++
成员函数重载的解释为

Aobject.operator++(0)

其中0是一个伪值

#include<iostream>
using namespace std;
class complex
{
    private:
        double real;                                    //实部 
        double imag;                                    //虚部 
    public:
        complex &operator ++();
        friend void output(complex &c);
        friend void intput(complex &c);
};
complex &complex::operator++ ()
{
    real=real+1;
    imag=imag+1;
}
void output(complex &c)
{
    cout<<"c++="<<"("<<c.real<<","<<c.imag<<"i)";
}

void intput(complex &c)
{
    cin>>c.real>>c.imag;
}

int main()
{
    complex c;
    intput(c);
    c++;
    output(c);
    
}

在这段代码编译时会提示:
[Error] no 'operator++(int)' declared for postfix '++' [-fpermissive]
编译器是DEVC++,在vs2010下也会警告,是编译器的问题吗

巴扎黑
巴扎黑

reply all(2)
PHPzhong
class complex
{
private:
    double real;                                    //实部 
    double imag;                                    //虚部 
public:
    complex &operator++() {  // prefix
        ++real; ++imag;
        return *this;
    }
    complex operator++(int) {  // postfix 注意返回值类型为值,不是引用
        auto ret = *this;
        ++*this;  // 使用已定义的 prefix operator++ ,避免逻辑重复
        return ret;
    }
    // other members
    // ...
};

int main() {
    complex c;
    
    ++c;  // 等价于下一行
    c.operator++();
    
    c++;  // 等价于下一行 
    c.operator++(0);
    
    return 0;
}
黄舟
complex &operator ++();

Your sentence is an overloading of the prefix ++ operator
The overload declaration of the C++ post++ operator can be implemented by adding an int inside (), that is:

 complex operator ++(int);    //后置++,返回值不是引用类型

In addition, your overloaded operator does not have a return statement, and the main function does not return 0;
It is best to implement both the copy constructor and the copy assignment operator.

complex & operator = (const complex &c)
{
    real = c.real;
    imag = c.imag;
    return *this;
}
complex complex::operator++ (int)    //后置++
{
    auto ret = *this;
    real = real + 1;
    imag = imag + 1;
    return ret;
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template