C++ 单目运算 and 双目运算符重载complex
2016-03-30 13:39
274 查看
1 单目运算
2 双目运算符重载complex.cpp
#include<iostream> using namespace std; //复数 class Complex{ public: double real,image; Complex()=default; Complex(double r, double i) :real(r),image(i){} ~Complex(){} Complex operator++(int i) { Complex tmp; tmp.real = this->real++; tmp.image = this->image++; return tmp; } Complex operator++() { this->real++; this->image++; return *this; } }; int main() { Complex c1(10,20); Complex c2; // c2 = c1++; c2 = ++c1; cout<<c1.real<<endl; cout<<c1.image<<endl; cout<<c2.real<<endl; cout<<c2.image<<endl; return 0; }
2 双目运算符重载complex.cpp
#include<iostream> using namespace std; //复数 class Complex{ public: double real,image; Complex()=default; Complex(double r, double i) :real(r),image(i){} ~Complex(){} Complex add(Complex c) { Complex tmp; tmp.real = this->real+ c.real; tmp.image= this->image+c.image; return tmp; } Complex operator+(Complex c) { Complex tmp; tmp.real = this->real+ c.real; tmp.image= this->image+c.image; return tmp; } friend Complex operator-(Complex c1,Complex c2); }; Complex operator-(Complex c1,Complex c2) { Complex tmp; tmp.real = c1.real - c2.real; tmp.image= c1.image-c2.image; return tmp; } int main() { Complex c1(10,20); Complex c2(10,20); Complex c3 ; c3 = c1+c2; // c3 = c1.add(c2); cout<<c3.real<<endl; cout<<c3.image<<endl; c1 = c3 - c3; cout<<c1.real<<endl; cout<<c1.image<<endl; return 0; }
相关文章推荐
- C++运算符重载范例
- c++ 运算符重载之成员函数重载
- C++复习笔记
- c++ 友元函数
- c++ static 类
- c语言:顺序栈的应用(二) 判断回文数
- 【Python】SWIG 和 Python——c/c++与脚本交互
- C++编译器函数模版机制剖析 - 函数模版的本质
- c++涉及继承和虚继承时的内存布局
- 作业:C++作业2
- 二分查找C++
- C++学习日志第四篇
- C++ 容器及选用总结
- 钻石型虚拟多重继承的C++对象内存模型
- 2016.3.29 360c++ 研发编程第二题
- 2016.3.29 360c++ 研发编程第一题
- C语言格式输入函数scanf()详解
- 1.c++笔记---有趣的bool型
- 【poj 1260】Pearls 题意&题解&代码(C++)
- c语言复习2值指针实战