C++实验22
来源:互联网 发布:linux 删除文件夹命令 编辑:程序博客网 时间:2024/05/21 18:42
一、类中类型转换函数重载
#include<iostream>using namespace std;#include<string>class student{ int idnum; char name[20]; bool gender; int age; float grade_eng; float grade_math; float grade_phy; float grade_cpp;public: student(int a, char *b, bool c, int d, float e, float f, float g, float h) {idnum=a;strcpy(name,b);gender=c;age=d;grade_eng=e;grade_math=f;grade_phy=g;grade_cpp=h;} void show() { cout<<"ID\tName\tSex\tAge\tEnglish\tMath\tPhysics\t\C++"<<endl; cout<<idnum<<'\t'<<name<<'\t'; if(gender) cout<<"Man\t"; else cout<<"Woman\t"; cout<<age<<'\t'<<grade_eng<<'\t'<<grade_math<<'\t'<<grade_phy<<'\t'<<grade_cpp<<endl; } operator float() { return (grade_eng+grade_math+grade_phy+grade_cpp)/4; }};void main(){ student stu(20170101,"Zhangsan",true,20,90.1,80,75.4,100); stu.show(); cout<<float(stu)<<endl;}
二、字符串类中运算符重载
//+=,==,-=,=,operator int#include<iostream>using namespace std;#include<string.h>class mystring{ char *str;public: mystring(char *p) { str=new char[strlen(p)+1]; strcpy(str,p); } mystring(){str=NULL;} ~mystring() {delete []str;} void show() { if(str) cout<<str<<endl; else cout<<"This str is NULL!\n"; } mystring operator =(mystring &a) //返回值未使用引用,因已自定义深拷贝构造函数 { if(str) { cout<<"if str"; delete []str; } str=new char[strlen(a.str)+1]; strcpy(str,a.str); return *this; } mystring & operator +=(mystring &a) { char *temp = new char[strlen(a.str)+strlen(str)+1]; strcpy(temp,str); strcat(temp,a.str); delete []str; str=temp; return *this; } mystring(mystring & a) { str=new char[strlen(a.str)+1]; strcpy(str,a.str); } friend bool operator ==(mystring &a,mystring &b);};bool operator ==(mystring &a, mystring &b){ if(strlen(a.str)!=strlen(b.str)) return false; for(int i=0;i<strlen(a.str);i++) if(a.str[i]!=b.str[i]) return false; return true;}void main(){ mystring a("张三"); a.show(); mystring b("李四"); b.show(); b+=a; b.show(); mystring c(a); cout<<(a==b)<<endl; cout<<(a==c)<<endl;}
阅读全文
0 0
- [C++]实验三
- c语言实验
- 哈希表实验C语言版
- C语言 枚举实验
- C-S通信实验
- C#-实验3
- C 实验总结
- C程序设计实验1
- C程序设计实验2
- c语言实验
- C++-实验-项目五
- C#—实验10.4
- C++---第七次实验。
- c++--补第二次实验
- C语言递归实验
- C语言实验-素数
- C+实验2
- C++STL 第二次实验
- Eclipse +python +PyDev 环境搭建
- 配置Maven,Tomcat,Svn的过程
- Multiple markers at this line
- Vim整理
- [转]Ubuntu上安装CRF++
- C++实验22
- iOS11拍照的HEIC图片无法显示
- git 拖下laravel 代码后报错 Warning: require(D:\WWW\laravel\bootstrap/../vendor/autoload.php
- Python_test00-01
- 将Eclipse代码导入到AndroidStudio时的问题汇总
- 堡垒机
- 针对JSON的一些初级理解
- 计蒜客 手机零件采购(简单背包)
- 补间动画代码实现