(C/C++学习笔记操作符重载入门)
2015-08-08 14:12
316 查看
#include "iostream" using namespace std; //a+bi class Complex { public: int a; int b; public: Complex(int a = 0, int b = 0) { this->a = a; this->b = b; } void printCom() { cout<<a<<"+"<<b<<"i"<<endl; } }; void main01() { Complex c1(1, 2), c2(3, 4); int a = 10, b = 20; a = a + b; //int 是基础类型,编译器已经为这些类型提供+操作了。 //c1 = c1 + c2; //c1的类型是 Complex,这种类型,是自定义类型。 编译器根本不知道如何加, //但是c++编译器会给你提供一个机制,让你实现自定义类型加 system("pause"); } Complex ComAdd(Complex &c1, Complex &c2) { Complex tmp; tmp.a = c1.a + c2.a; tmp.b = c1.b + c2.b; return tmp; } Complex operator+(Complex &c1, Complex &c2) { Complex tmp; tmp.a = c1.a + c2.a; tmp.b = c1.b + c2.b; return tmp; } void main() { Complex c1(1, 2), c2(3, 4); //Complex c3 = ComAdd(c1, c2); //Complex c3 = operator+(c1, c2); Complex c3 = c1 + c2; c3.printCom(); system("pause"); }
相关文章推荐
- 10-0. 说反话 (20)
- 简单的c语言
- Effective C++:规定12:不要忘了复制的对象时,它的每一个组成部分
- C语言结构体学习系列之(一)
- 剑指offer刷题之c++实现的根据二叉树的前序和中序遍历重建二叉树
- 剑指offer刷题之c++实现的旋转数组的最小数字
- 剑指offer刷题之c++实现的调整数组顺序使奇数位于偶数前面
- 剑指offer刷题之c++实现的反转链表
- 剑指offer刷题之c++实现的合并两个有序的链表
- 剑指offer刷题之c++实现的替换空格
- 剑指offer刷题之c++实现的求链表中倒数第k个值
- C++数组
- Leetcode -- Roman to Integer
- C++设计模式——单例模式
- 用最小最大的两个数交换首尾两数
- Caesar cipher
- c++ stl string char* 向 string 转换的问题
- C/C++程序基础
- C++静态库和动态库
- 分数相加减的代码(c++)