博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
86.运算符重载
阅读量:4316 次
发布时间:2019-06-06

本文共 1790 字,大约阅读时间需要 5 分钟。

1 #define _CRT_SECURE_NO_WARNINGS 2 #include 
3 using namespace std; 4 5 class mystring 6 { 7 public: 8 char *pstr; 9 int length;10 mystring():pstr(nullptr),length(0)11 {12 13 }14 15 mystring(char *str)16 {17 //获取字符串长度18 this->length = strlen(str) + 1;19 this->pstr = new char[this->length + 1];20 //拷贝21 strcpy(this->pstr, str);22 }23 24 //拷贝构造25 mystring(const mystring &my)26 {27 this->length = my.length;28 this->pstr = new char[this->length];29 strcpy(this->pstr, my.pstr);30 }31 32 mystring add(const mystring &my)33 {34 int n = this->length + my.length - 1;35 mystring temp;36 temp.length = n;37 //分配内存38 temp.pstr = new char[temp.length];39 strcpy(temp.pstr, this->pstr);40 //尾部添加41 strcat(temp.pstr, my.pstr);42 return temp;43 }44 45 //重载加法46 mystring operator +(const mystring &my)47 {48 int n = this->length + my.length - 1;49 mystring temp;50 temp.length = n;51 //分配内存52 temp.pstr = new char[temp.length];53 strcpy(temp.pstr, this->pstr);54 //尾部添加55 strcat(temp.pstr, my.pstr);56 return temp;57 }58 };59 60 template
61 T add(T a, T b)62 {63 return a + b;64 }65 66 void main()67 {68 mystring str1 = "hello";69 mystring str2 = "world";70 //mystring str3 = str1.add(str2);71 //mystring str3 = str1 + str2;72 mystring str3 = str1.operator+(str2);73 cout << str3.pstr << endl;74 75 //模板与运算符重载76 cout << add
(str1, str2).pstr << endl;77 cin.get();78 }

 

转载于:https://www.cnblogs.com/xiaochi/p/8595100.html

你可能感兴趣的文章
B站 React教程笔记day2(3)React-Redux
查看>>
找了一个api管理工具
查看>>
Part 2 - Fundamentals(4-10)
查看>>
使用Postmark测试后端存储性能
查看>>
NSTextView 文字链接的定制化
查看>>
第五天站立会议内容
查看>>
CentOs7安装rabbitmq
查看>>
(转))iOS App上架AppStore 会遇到的坑
查看>>
解决vmware与主机无法连通的问题
查看>>
做好产品
查看>>
项目管理经验
查看>>
笔记:Hadoop权威指南 第8章 MapReduce 的特性
查看>>
JMeter响应数据出现乱码的处理-三种解决方式
查看>>
获取设备实际宽度
查看>>
Notes on <High Performance MySQL> -- Ch3: Schema Optimization and Indexing
查看>>
Alpha冲刺(10/10)
查看>>
数组Array的API2
查看>>
为什么 Redis 重启后没有正确恢复之前的内存数据
查看>>
No qualifying bean of type available问题修复
查看>>
第四周助教心得体会
查看>>