您的位置:首页 > 编程语言 > C语言/C++

实现C++类中对于前置++,后置++的重载

2017-03-06 18:20 176 查看
建立一个复数类,在类中实现构造函数、析构函数、拷贝构造和运算符重载

在运算符重载的实现过程中,可以发现,前置++和后置++在实现上有区别

由于前置++是先实现++,再进行使用,所以在实现过程中比较简单

而后置++需要先使用,再进行++操作

在以下程序中,实现了几个默认成员函数和前置++与后置++

#include
using namespace std;

class Complex
{
private:
double _real;
double _image;
public:
Complex(double real=0.0, double image=0.0)     //构造函数
{
_real = real;
_image = image;
cout << "Complex()" << endl;
}
~Complex()     //析构函数
{
cout << "~Complex" << endl;
}
Complex(Complex &com)   //拷贝构造函数
{
_real = com._real;
_image = com._image;
cout << "Complex(Complex& com)" << endl;
}
void Display()
{
cout << _real << "+" <<"("<< _image << "i)" << endl;
}
Complex operator+(Complex &com)   //加号重载
{
Complex tmp;
tmp._real = _real + com._real;
tmp._image = _image + com._image;
return tmp;
}
Complex Add(Complex& com)   //加号
{
Complex tmp;
tmp._real = _real + com._real;
tmp._image = _image + com._image;
return tmp;
}
Complex operator-(Complex &com)  //减号重载
{
Complex tmp;
tmp._real = _real - com._real;
tmp._image = _image - com._image;
return tmp;
}
Complex& operator=(Complex& com)   //赋值运算符的重载
{
if (this != &com)
{
_real = com._real;
_image = com._image;
}
return *this;   //返回引用
}
Complex& operator+=(Complex& com)     //加等重载
{
_real += com._real;
_image += com._image;
return *this;
}
Complex& operator-=(Complex& com)    //减等重载
{
_real -= com._real;
_image -= com._image;
return *this;
}

Complex& operator++()   //前置++
{
_real = _real + 1;
_image = _image + 1;
return *this;
}
Complex operator++(int)     //后置++
{
Complex cmp(*this);
_real++;
_image++;
return cmp;
}

};

int main()
{
Complex C1(3.0, 3.0);
Complex C2(3.0, 3.0);
C1++.Display();
C1.Display();
(++C1).Display();
C1.Display();
return 0;
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: