友元的简单应用

1,对象 + 对象,或者,对象 + 数字,可以用类的成员函数去重载+号函数,但是,数字 + 对象就不能用类的成员函数去重载+号函数了,

因为编译器会把数字 + 对象翻译成数字.operator+(const 类 &对象),因为数字不是类的对象,无法传递给类的成员函数this指针。

用友元去重载:数字 + 对象

2,用友元去重载:>>运算符和<<运算符。

其实用类的成员函数也可以重载<<运算符,但是使用起来比较怪异,不能使用cout << 对象,只能使用对象 << cout。

#include <iostream>
using namespace std; class Imaginary{
friend Imaginary operator+(int i, const Imaginary &m);
friend ostream& operator<<(ostream &os, const Imaginary &m);
friend istream& operator>>(istream &is, Imaginary &m);
public:
Imaginary():real(0), imag(0){
cout << "c:" << this << endl;
}
Imaginary(int real, int imag):real(real), imag(imag){
cout << "c:" << this << endl;
}
Imaginary operator+ (const Imaginary &m){
return Imaginary (real + m.real, imag + m.imag);
}
Imaginary operator+ (int i){
return Imaginary(real + i, imag);
}
Imaginary& operator= (const Imaginary &m){
cout << "asign" << endl;
if(this != &m){
real = m.real;
imag = m.imag;
}
return *this;
}
ostream& operator<<(ostream& os){
os << "[" << real << "," << imag << "]";
return os;
}
~Imaginary(){
cout << this << endl;
}
private:
int real;
int imag;
};
Imaginary operator+(int i, const Imaginary &m){
return Imaginary(i + m.real, m.imag);
} ostream& operator<<(ostream &os, const Imaginary &m){
os << "(" << m.real << "," << m.imag << ")";
return os;
}
istream& operator>>(istream &is, Imaginary &m){
is >> m.real >> m.imag;
return is;
}
int main(){
Imaginary m1(10, 20);
Imaginary m2(1, 2);
Imaginary m3 = m1 + m2;
Imaginary m4 = m1 + 10;
Imaginary m5 = 20 + m1;
cout << "a" << m5 << "aa" << endl;;
m5 << cout << "bb" << endl;
Imaginary m6;
cin >> m6;
cout << m6 << endl;
return 0;
}

最新文章

  1. TTAS Lock C++11 实现
  2. Dropplets – 极简的 Markdown 博客平台
  3. selenium测试套件
  4. .net 后台中对html标签按钮跳转后台以及后台简单验证
  5. 什么是REST架构(转)
  6. 申请Android Map 的API Key(v2)的最新申请方式(SHA1密钥)
  7. 设置N秒后执行某个方法或函数
  8. flask开发restful api系列(8)-再谈项目结构
  9. java ReentrantLock结合条件队列 实现生产者-消费者模式 以及ReentratLock和Synchronized对比
  10. Springboot Selenide UI 自动化测试
  11. 第二次作业-git的基本操作
  12. linux 文件搜索
  13. 同时安装python2.7和python3.5
  14. 《Linux内核设计与实现》Chapter 1 读书笔记
  15. Java设计模式(13)模板模式(Template模式)
  16. linux shell搜索某个字符串,然后在后面加上字符串?字符串后面插入字符串?sed字符串后面插入字符串?
  17. order by having group by
  18. 《FPGA全程进阶---实战演练》第三章之PCB设计之过孔
  19. linux系统挂载NTFS移动硬盘
  20. unity自带寻路Navmesh入门教程

热门文章

  1. 【golang-GUI开发】项目的编译
  2. Handsontable Dropdown with key-value pair
  3. 先装IIS后装.Net Framework
  4. swoole扩展实现真正的数据库连接池
  5. 【Spring】28、Spring中基于Java的配置@Configuration和@Bean用法.代替xml配置文件
  6. 事件处理程序 (DOM0级)
  7. 【20190223】HTTP-知识点整理:HTTPS
  8. JavaScript面向对象编程指南(三) 函数
  9. loadrunner&#160;脚本录制-Protocol&#160;Advisor协议分析器的使用
  10. 浅谈EditText控件的inputType类型