当前位置: 首页 > news >正文

C++操作符重载的注意事项

关于C++操作符重载,可以用类内的成员运算符重载或友元函数。但是注意两个不能同时出现,不然编译出错。

#include<iostream>
using namespace std;
class Complex{public:Complex(int r=0,int i=0){real = r;imag = i;}//#if 0Complex operator+(Complex &c) {cout << " internal function is called" << endl;Complex c2;c2.real = this->real + c.real;c2.imag = this->imag + c.imag;return c2;}
//    #endif void print();friend Complex operator+(int a,Complex &c2); //声明友元运算符重载函数,+的左侧是整数,右侧是类的对象 friend Complex operator+(Complex c1,int a);//声明友元运算符重载函数,+的右侧是整数,左侧是类的对象
//     friend Complex operator+(Complex c1,Complex c2);//声明友元运算符重载函数,+的右侧是整数,左侧是类的对象 private:int real;int imag;
};
Complex operator+(int a,Complex &c2)  //定义友元运算符重载函数,+的左侧是整数,右侧是类的对象 
{Complex temp;cout << "friend function 1 is called" << endl;temp.real = a+c2.real;temp.imag = c2.imag;return temp;
}
Complex operator+(Complex c1,int a)//定义友元运算符重载函数,+的右侧是整数,左侧是类的对象 
{Complex temp;cout << "friend function 2 is called" << endl;temp.real = c1.real+a;temp.imag = c1.imag;return temp;
} 
#if 0
Complex operator+(Complex c1,Complex c2)
{Complex temp;cout << "friend function 3 is called" << endl;temp.real = c1.real+c2.real;temp.imag = c1.imag+c2.imag;return temp;
}
#endifvoid Complex::print()
{cout<<real<<"+"<<imag<<'i'<<endl;
}int main()
{Complex co1(30,40),co2(30,40),co3,co4;co1.print();co3=100+co1;  //co3=operator+(100,co1); co3.print();co3=co2+100;  //co3=operator+(co2,100);co3.print();co4=co2+co3;co4.print();return 0;
}
http://www.lryc.cn/news/151468.html

相关文章:

  • 10 | Spark 查找每个单词的最大行号
  • CRE66365
  • React hook 10种常见 Hook
  • 图文详解PhPStudy安装教程
  • stable diffusion实践操作-hypernetworks
  • Win10搭建VisualSvn Server
  • Golang网络编程
  • 详解vue3中ref和reactive用法和区别
  • QML与C++的交互操作
  • Java_理解方法调用
  • Mysql 性能分析(慢日志、profiling、explain)、读写分离(主从架构)、分库分表(垂直分库、垂直分表、水平分表)
  • 获取Linux内核源码
  • 【Maven教程】(四)坐标与依赖:坐标概念,依赖配置、范围、传递性和最佳实践 ~
  • Java“牵手”京东店铺所有商品API接口数据,通过店铺ID获取整店商品详情数据,京东店铺所有商品API申请指南
  • TuyaOS开发学习笔记(1)——NB-IoT开发搭建环境、编译烧写(MT2625)
  • Css 将div设置透明度,并向上移50px,盖住上面的元素一部分
  • HTTPS安全通信和SSL Pinning
  • PHP自己的框架PDO数据表前缀、alias、model、table、join方法实现(完善篇九--结束)
  • 华为OD:敏感字段加密
  • IDEA新建SpringBoot项目时启动编译报错:Error:java: 无效的源发行版: 17
  • 【云原生进阶之PaaS中间件】第一章Redis-2.3.3集群模式
  • 游戏发行商能够提供什么服务?
  • Linux 多进程解决客户端与服务器端通信
  • Scala的模式匹配
  • HttPClient简介及示例:学习如何与Web服务器进行通信
  • STS4 New 安装Spring Bean Configuration File
  • Java经典面试题(异或运算)
  • No primary or single unique constructor found for interface java.util.List
  • C#关于WebService中File.Exists()处理远程路径的异常记录
  • JavaWeb_LeadNews_Day10-Xxljob, Redis实现定时热文章