C++:友元运算符重载函数
2015-08-26 16:11
357 查看
运算符重载函数:实现对象之间进行算数运算,(实际上是对象的属性之间做运算),包括+(加号)、-(减号)、*、/、=、++、--、-(负号)、+(正号)
运算符重载函数分为:普通友元运算符重载函数、成员友元运算符重载函数、成员运算符重载函数
运算符运算符重载函数按运算类型为:双目运算符重载函数,如加、减、乘、除、赋值; 单目运算符重载函数:自加、自减、取正负号
切记:成员运算符. 和->,sezeof等不能重载。运算符重载函数的参数至少有一个是类类型或引用类型,
下面为友元运算符重载函数举例:
运行结果:
运算符重载函数分为:普通友元运算符重载函数、成员友元运算符重载函数、成员运算符重载函数
运算符运算符重载函数按运算类型为:双目运算符重载函数,如加、减、乘、除、赋值; 单目运算符重载函数:自加、自减、取正负号
切记:成员运算符. 和->,sezeof等不能重载。运算符重载函数的参数至少有一个是类类型或引用类型,
下面为友元运算符重载函数举例:
#include<iostream> using namespace std; class Complex { public: Complex(double r=0.0,double i=0.0); void print(); //friend为友元函数的关键字,这两个符号运算符重载函数的参数类型至少有一个类类型或者类的引用 friend Complex operator+(Complex &a,Complex &b); friend Complex operator-(Complex &a,Complex &b); private: double real; double imag; }; Complex::Complex(double r,double i) //在类外定义函数,需要用::作用域符号 { real = r; imag = i; } Complex operator+(Complex &a,Complex &b) { Complex temp; //创建一个临时对象 temp.real = a.real + b.real; temp.imag = a.imag + b.imag; return temp; } Complex operator-(Complex &a,Complex &b) { Complex temp; //创建一个临时对象 temp.real = a.real - b.real; temp.imag = a.imag - b.imag; return temp; } void Complex::print() { cout<<real; if(imag>0) cout<<"+"; if(imag!=0) cout<<imag<<'i'<<endl; } int main(int agrs,const char *agrv[]) { Complex A1(2.3,4.6),A2(3.6,2.8),A3,A4; A3 = A1 + A2;//A3 = operator+(A1,A2); //对运算符重载函数的调用,前面的为隐式调用,后面的为显示调用 A4 = A1 - A2;//A4 = operator-(A1-A2); A1.print(); A2.print(); A3.print(); A4.print(); return 0; }
运行结果:
2.3+4.6i 3.6+2.8i 5.9+7.4i -1.3+1.8i Program ended with exit code: 0
相关文章推荐
- LeetCode:Binary Tree Paths
- WIN10或WIN8.1系统下MDK“the arm c/c++ compiler 已停止工作”解决办法之一
- 深入学习C语言中memset()函数的用法
- 《算法导论》中的查找任意顺序值的C++实现
- c,c++库函数、win32库函数、mfc
- c和c++交互编译
- 【C++】单链表的基本操作
- C语言连接MySQL数据库
- 用CPPUnit做单元测试
- 【C++】万年历(时间计数器)
- 【C++】模拟string类的实现(string 类的深拷贝)
- 详解C语言中的memset()函数
- C/C++面试题(一)
- C++ 释放vector中的元素
- C++new和delete实现原理
- C++ 将string转换成char*字符串
- C++11 智能指针
- C语言malloc和free实现原理
- 动态分配三维数组
- OutMan——C语言中字符串处理函数、内存管理和内存分区