实现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; }
相关文章推荐
- 关于类重载前置++和后置++的骚操作
- [置顶] # c++运算符重载之 前置++, 后置++, 负号运算符, 类型转换函数, 以及输入输出运算符
- 实现前置与后置递增(递减)运算符的重载
- 对于C++中的前置++和后置++的看法
- 三论在C++类中实现Windows窗口的创建
- 用char*实现的一个完整的类,包含类的基本操作:一般构造、拷贝构造、赋值转换、重载 > >,< <
- 在C++类中实现Windows窗口的创建
- 如何实现JS函数的重载
- 如何在vb.net中实现对类变量的重载
- 用Lostinet的ContextBoundModel来实现前置和后置条件检查
- 简单的模板实例,实现简单的运算符重载
- JScript重载的另类实现
- 对《在C++类中实现Windows窗口的创建》一文的补充
- Effective C# 原则20:明辨接口实现和虚函数重载的区别(译)
- 如何实现js的重载
- 看了一下MD5加密算法的介绍,然后顺手把C实现改成了个C++类。
- 在C++类中实现Windows窗口的创建
- OOP基本概念之讨论:重载也是实现多态的一种方法吗?
- 对《在C++类中实现Windows窗口的创建》一文的补充
- [原创]我的WCF之旅(5):面向服务架构(SOA)和面向对象编程(OOP)的结合——如何实现Service Contract的重载(Overloading)