关于C++类中++的运算符重载问题,后置自增表达式不行?

浏览:36日期:2023-05-11

问题描述

在程序设计基础这本书中写的是: 后置自增表达式 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下也会警告,是编译器的问题吗

问题解答

回答1:

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;}回答2:

complex &operator ++();

你这句是前置++操作符的重载C++后置++操作符的重载声明可以在()里面加个int来实现,即:

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

另外,你的重载操作符也没有return语句,main函数也没return 0;最好是拷贝构造函数、拷贝赋值运算符都实现下。

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;}

相关文章: